---
title: 'Models: functions a whole site shares'
description: Use this guide when the same logic repeats from page to page, when a
  table's rows need methods of their own, or when a row must pass a rule before it
  is saved.
sidebar:
  order: 19
---

Use this guide when the same logic repeats from page to page, when a table's
rows need methods of their own, or when a row must pass a rule before it is
saved. A model is a file of functions that every page, layout and component
of the site may call by name, with no import.

## Where a model goes

A model is `models/<Name>.ts`, directly in `models/`, named as a component
is (`Price`, `Shown`). The whole file is script, with no markup and no
`<script>` tag. Its top level holds `export function`, `export const` with a
literal value, and unexported `function` and `const`, which only the file
itself reads. Nothing runs when a model loads: no `let`, no loop and no
statement at the top.

```ts
// models/Shown.ts
const DAY = "dd.MM.yyyy"

export function date(day) {
  return formatDate(day, DAY)
}
```

## Calling a model

Any file calls a model's exported function by the model's name:
`{Shown.date(row.published_on)}`. Only functions are reached from outside,
so `{Price.CURRENCY}` is refused: export a function that answers it.

A model function reads its parameters, its own file's names, other models,
and `tables`, `site`, `session`, `today()` and `assets`. It never reads
`params`, `query`, `page`, `props`, `form`, `forms`, `fields` or `consent`;
the caller passes in what it needs.

These are refused:

- a model named like a component, a table, or a name the language already
  has;
- anything else named after a model: a parameter, a `const`, a function or a
  loop item called `Price` beside `models/Price.ts`;
- models that call each other in a cycle;
- more than 50 models, or a model that exports more than 50 functions.

## Writing through a model

A function that writes (`insert`, `update`, `delete`, `notify`, `redirect`
or `fail`), itself or through another model, may be called from a form's
function and is refused where a page draws. A form may also run a model's
function directly, which is how two pages share one form:

```html
<form id="join" action={Signup.join}>
```

A workflow's Run JavaScript step cannot call a model: its script runs apart
from the site's files. A row it hands to a later step is still judged by the
table's model when that step writes it.

## A model for a table

`export const table = "posts"` gives the `posts` table this model. A table
has at most one.

- An exported function whose first parameter is `row` becomes a method of
  each row: `post.readingTime()` runs `Post.readingTime(post)`.
- Every other exported function is called on the table:
  `tables.posts.teaser(3)` runs `Post.teaser(3)`. A page does that only on a
  table visitors may read.
- A row function named like one of the table's fields or a method rows and
  tables already have is refused.
- `post?.readingTime()` is refused: write
  `post ? post.readingTime() : null`, so a missing row draws nothing.
- Call a model on the session's row by its name:
  `Person.greeting(session.row)`.
- Where the check cannot tell that a value is a row of the table, as in
  `tables.posts.latest(1)[0]`, call the model by name:
  `Post.readingTime(tables.posts.latest(1)[0])`.

## A rule a row must pass

A model for a table may `export function validate(row)`. It runs on every
row written to that table, before the row is saved, whoever writes it: a
visitor's form, the owner, a tool or a workflow.

- `row` is the row as it would be saved, with its `slug` and `url` where it
  has them. On a new row `row.id` is nothing; on a change it is the row's
  own number. A reference reads the row it points at, but one to a table
  only the owner reads is nothing, whoever writes the row.
- It reads as a page reads, and writes nothing.
- `fail({ price: "Must be above 0" })` refuses the row with that sentence
  under the `price` field, and `fail({ slug: "Taken" })` under its slug. A
  field the table does not have is refused. `fail("...")` refuses the whole
  row. A `validate` that returns without `fail` lets the row through.
- The sentence is the site's own and is shown as written. It may not carry
  text a visitor typed, such as `fail(row.title)` on a table visitors write:
  that is refused. There the row's `slug` and `url` are a visitor's text too.
- A `validate` that faults refuses the row.
- `validate` is no method of a row or of the table: `post.validate()` and
  `tables.posts.validate(...)` are refused.
- Like any change to the site's files, a new or changed `validate` applies
  once its branch is merged.

```ts
// models/Post.ts
export const table = "posts"

export function readingTime(row) {
  return ceil(row.body.length / 1500)
}

export function validate(row) {
  const same = tables.posts.count(p => p.title == row.title && p.id != (row.id ?? 0))
  if (same > 0) {
    fail({ title: "A post has this title already." })
  }
}
```

`p.id != (row.id ?? 0)` leaves the row itself out when it is changed, so
saving a post again does not count its own title.
