Defining Models
Models define the content types in your project. Each model has a key, a name, and a set of typed fields that describe what data it holds.
Model Interface
interface ApplyConfigModelInput {
key: string; // Unique identifier (e.g., 'blog-post')
name: string; // Display name (e.g., 'Blog Post')
pluralName?: string; // Plural display name
pluralKey?: string; // Plural key
description?: string; // Model description
fields?: FieldDefinitionInput[]; // Field definitions
config?: Record<string, unknown>; // Additional model configuration
access?: AccessInput; // Owner plane + default visibility (see Model Access)
lookups?: LookupDefinitionInput[]; // Indexed access paths (see Lookups below)
}Basic Example
import { defineConfig, defineModel } from '@foir/cli/configs';
export default defineConfig({
key: 'my-blog',
name: 'My Blog',
models: [
defineModel({
key: 'blog-post',
name: 'Blog Post',
fields: [
{ key: 'title', type: 'text', label: 'Title', required: true },
{ key: 'slug', type: 'text', label: 'Slug', required: true },
{ key: 'excerpt', type: 'text', label: 'Excerpt', config: { widget: 'textarea' } },
{ key: 'body', type: 'prose', label: 'Body' },
{ key: 'publishDate', type: 'date', label: 'Publish Date' },
{ key: 'featured', type: 'boolean', label: 'Featured' },
],
}),
],
});Field Definitions
Each field in a model is defined with the FieldDefinitionInput interface:
interface FieldDefinitionInput {
key: string; // Unique field key within the model
type: string; // Field type (see table below)
label?: string; // Display label in the editor
required?: boolean; // Whether the field must be filled
queryable?: boolean; // Allow filtering/sorting on this field (see below)
embed?: boolean; // Embed this field for AI search; omit to follow the type default
helpText?: string; // Guidance shown below the field
placeholder?: string; // Placeholder text for input fields
defaultValue?: unknown; // Pre-filled value for new records
config?: Record<string, unknown>; // Type-specific configuration
itemType?: string; // Item type for list fields
storage?: string; // Storage configuration
templateZone?: string; // Template zone assignment
zoneOrder?: number; // Order within the template zone
guarded?: { read?: boolean; write?: boolean }; // Which sides take the field's own grant
}Using defineField
The defineField helper is useful when you want to reuse field definitions across multiple models:
import { defineConfig, defineField } from '@foir/cli/configs';
const seoTitle = defineField({
key: 'seoTitle',
type: 'text',
label: 'SEO Title',
helpText: 'Appears in search engine results. Keep under 60 characters.',
placeholder: 'Enter SEO title...',
});
const seoDescription = defineField({
key: 'seoDescription',
type: 'text',
config: { widget: 'textarea' },
label: 'SEO Description',
helpText: 'Appears in search engine results. Keep under 160 characters.',
});
export default defineConfig({
key: 'my-site',
name: 'My Site',
models: [
{ key: 'page', name: 'Page', fields: [seoTitle, seoDescription] },
{ key: 'blog-post', name: 'Blog Post', fields: [seoTitle, seoDescription] },
],
});Available Field Types
| Type | Description | Example Use |
|---|---|---|
text | Single- or multi-line text (set config.widget: 'textarea' for multi-line) | Titles, names, slugs, excerpts |
prose | Translatable rich text, with models placed inline where config.allowedTypes admits them | Blog body, long-form pages, marketing layouts |
integer | Whole numbers | Quantities, priorities, display order |
decimal | Exact decimals, carried as a string | Prices, rates, measurements |
boolean | Yes/no toggle | Feature flags, visibility |
date | Date picker (can include time) | Publish dates, event dates |
enum | Inline {label, value} choices (defineEnumField) | Status, category, type |
select | Record-backed choice — options come from records of optionModelKey (defineSelectField) | Author, tag, related lookup table |
reference | Reference to another record | Author, related posts |
model | A model key, stored as a string (a list of them when multiple). It names a model, not a record | The target model of a config record |
image | Image upload | Hero images, thumbnails |
video | Video upload (HLS on Pro and Enterprise plans) | Embedded videos |
file | Generic file upload | PDFs, documents |
list | Ordered list of items (itemType controls inner type) | Bullet points, tag arrays |
geopoint | A latitude/longitude point. Declaring one materialises it into the PostGIS subsystem behind proximity queries, so records become searchable by distance | Store locations, delivery areas, event venues |
json | Raw JSON | Untyped payloads |
To embed an inline model’s value (an address, an SEO block), use the inline model’s key as the field’s type.
prose is text only unless it says otherwise: config.allowedTypes names the inline models and the media primitives it will admit — image, video, file, reference and geopoint, and config.passages: false makes it an arranger with no typing at all. It replaces the old richtext and flexible pair — one representation, one walker, one projection. See Field Types for the full shape.
text and prose fields are translatable without any setting. Set config.translatable to false on one that holds a link, an anchor, a key or a slug, and it is left out of translation: translation tools do not offer it, and a translation written to it is refused:
{ key: 'href', type: 'text', label: 'Link URL', config: { translatable: false } }Only false opts out. See Localization for how translations are stored and served.
Enum Fields
enum is the inline-choice type: the options are declared in the config as an { label, value } array. Use defineEnumField so TypeScript enforces the shape.
import { defineEnumField } from '@foir/cli/configs';
defineEnumField({
key: 'status',
type: 'enum',
label: 'Status',
required: true,
config: {
options: [
{ value: 'draft', label: 'Draft' },
{ value: 'review', label: 'In Review' },
{ value: 'published', label: 'Published' },
{ value: 'archived', label: 'Archived' },
],
multiple: false, // Allow selecting more than one value
default: 'draft', // Default value (or array when multiple)
},
})Each value is the wire value: the record stores it and the data API serves it exactly as written, so it must be a valid GraphQL enum value. See defineEnumField for the rule a push enforces.
Select Fields
select is record-backed: the options come from the records of another model, named via optionModelKey. Inline { label, value } options do not compile on a select field — use enum for those. Use defineSelectField for the typed config.
import { defineSelectField } from '@foir/cli/configs';
defineSelectField({
key: 'category',
type: 'select',
label: 'Category',
required: true,
config: {
optionModelKey: 'category', // records of this model become the options
multiple: false, // Allow selecting more than one record
},
})Lookups
lookups declares indexed access paths on a model so records can be fetched by a key other than the primary id. Each lookup names the ordered scalar field keys that make up the key via keyBy; composites are first-class.
defineModel({
key: 'redirect',
name: 'Redirect',
fields: [...],
lookups: [
{ keyBy: ['fromHost', 'fromPath'] }, // composite lookup
{ keyBy: ['slug'], name: 'redirectBySlug' }, // override generated query name
],
})keyBy lists top-level scalar fields only. name overrides the generated GraphQL query field name; omit it for the default <typeLowerCamel>By<PascalCaseKeyFields>. The platform validates existence, scalar type, top-level-only, and caps (4 lookups, 4 fields) at push time.
A lookup’s query is a root field of the project’s API, so its name is the project’s, not the model’s. A name another model’s lookup, a model’s own queries, a query operation or a built-in query already has is refused at push, and the refusal names what holds it. Two lookups on one model need different names, and two lookups keyed by the same fields need a name on one of them.
Keys the platform will refuse
Your project’s GraphQL schema has one flat namespace covering every named type, and the platform fills part of it. A model key becomes a type name (blog-post becomes BlogPost), so a key that lands on a name already in use is refused when you push, naming what it collided with.
There are two ways that happens.
Platform names. Over 230 type names are on every project’s schema: PageInfo, SortDirection, TextWhereInput, Visibility, AuthUser, SearchResult and so on. A key deriving one of them is refused. Most are unsurprising, but a few read as ordinary content keys, so the refusal names the type and you pick another key.
Names your own project derives. Every model generates a family of types around itself, so a model keyed page puts Page, PageConnection, PageEdge, PageWhereInput, PageOrderByInput, PageSearchResult, PageUpdateInput, PageWritePayload and CreatePageInput into the namespace. A model keyed page-connection collides with the second of those. Each enum or select field adds three more (PageStatusEnum, PageStatusEnumSetInput, PageStatusEnumWhereInput for a status field), and each list field adds ListSpliceInput, ListUpdateInput and ListWhereInput types the same way.
A polymorphic reference does the same. A field admitting page and product generates a union named PageProductRef, shared by every field with the same targets, so page-product-ref is taken in that project and free in one without such a field.
The second kind moves. Widening a reference field to admit another model generates a union name the project did not have before, so a push that only edits a field can be refused because of a model key written months earlier. The refusal names the field and the models it admits; either rename the model or narrow the field.
Naming a union yourself
A reference field admitting two or more models can name its union with unionName:
{
key: 'target',
type: 'reference',
label: 'Target',
config: {
referenceTypes: ['page', 'product'],
unionName: 'Linkable',
},
}A name you choose does not move. Adding a model to the project cannot land on it, and admitting another model in the field changes its members, not its name. The name is checked like any other: it must be a GraphQL type name, it cannot be one of the platform’s own, and no model key or other derived name can already hold it. Two fields may give the same name only when they admit the same models, because one name over two sets of models would be two types. A reference to one model returns that model’s own type rather than a union, so a unionName on it is refused.
In the console, the field editor offers Union name once a reference admits two or more models.
The published schema is checked too
Your project serves a draft schema and a published one, and each is its own namespace. Publishing, unpublishing and rolling back a release are refused when they would leave the published schema with one name twice, and so is discarding a draft that would do the same to the draft schema. Unpublishing is the one that surprises: a union named from its models is named from the models that are published, so unpublishing article renames the union a field over page, product and article returns, and that new name can be taken. A union you have named yourself is not renamed this way.
Queryable Fields
Any declared field can be filtered on in where, but only a queryable: true field is registered for the typed-filter side table, which makes filtering on it fast and lets you sort by it. Without it, a filter on the field takes a slow path and the platform rejects sorting by it.
{ key: 'priority', type: 'integer', label: 'Priority', queryable: true }Guarded Fields
A field follows its model: whoever reads a model’s records reads the field, and whoever writes them writes it. Mark a side of a field guarded to take it out of the model’s grants:
{
key: 'cancelToken',
type: 'text',
label: 'Cancel token',
guarded: { read: true, write: true },
}A guarded side is read, or written, only by a holder of the grant that names the field: records:read:<model>.<field> or records:write:<model>.<field>. The reach works as it does on a model. Written without one, the grant reaches the holder’s own records, and with .all it reaches every owner’s. A grant on the model doesn’t reach a guarded side. A grant on every owner’s records of every model does, which is how the two built-in bundles, project:manage and tenant:manage, hold every field.
Give the field’s grants to whatever should read or write it: a role, a key or an operation. An operation holds the grants it declares, whoever it runs for, so a field that only the operation reads and writes is given to the operation and to no user’s role:
defineOperation({
key: 'cancel_order',
name: 'Cancel order',
endpoint: '/orders/cancel',
grants: [
'records:read:order',
'records:write:order',
'records:read:order.cancelToken',
'records:write:order.cancelToken',
],
});The user who runs it is still the user the operation’s token carries, for ownership, row confinement, the audit actor and quotas. A user’s own request, from their browser, holds what their roles give them and nothing of the operation’s.
A write that names a guarded field its caller doesn’t reach is refused, and the refusal names the grant the field takes. Writing a field on a new record takes the same grant as changing it, and so does a copy of a record that holds a value in it. A save of a record’s whole content replaces what its writer can see: a guarded field they don’t reach, left out of the content, keeps the value it holds, and one sent back unchanged isn’t a write of it. The console shows such a field as withheld, not empty: the records service names each guarded field it held back on the record it answers with (withheldFields). On the data API a guarded field the caller doesn’t read resolves to null, and filtering or sorting on it takes its read at .all, because a filter compares the field on every record the list matches, not only the caller’s. A response cached for one caller is never served to a caller who reads different guarded fields.
A record’s live editing room holds its whole working copy, and everyone in the room is sent all of it. So joining the room of a record with guarded fields takes the read of each field guarded for read, and joining it to edit takes the write of each field guarded for write as well, at the reach the record needs.
A field’s access list, which named kinds of caller, is refused on push by name, with the field to guard and the grants to give.
Model Config Options
The config object on a model carries its capability flags:
{
key: 'product',
name: 'Product',
fields: [...],
config: {
versioning: true, // Keep a version history of every change
publishing: true, // Draft → published workflow (implies versioning)
variants: true, // Per-audience content variants (implies publishing)
inline: false, // Usable as a field type inside other models
},
}| Option | Type | Description |
|---|---|---|
versioning | boolean | Keep a version history of every change |
publishing | boolean | Enable the draft → published workflow. Implies versioning. |
variants | boolean | Per-audience content variants. Implies versioning + publishing. |
embeddings | boolean | Maintain vector embeddings of this model’s prose. Record-bearing only. See AI & Search. |
inline | boolean | Expose this model as a field type embeddable in other models, instead of a top-level public type |
Every non-inline model is automatically queryable through the public API — there is no separate “expose” flag. inline models aren’t queryable on their own; they’re embedded as field values in other models.
Record ownership (who owns a model’s records, and their default visibility) is the separate top-level access field — see Model Access below.
Model Access
access declares which plane owns records of this model and what visibility new records start at — the broad layer of Foir’s unified resource-access model. It mirrors the console’s model Owner plane control, and foir push reconciles it onto the model.
{
key: 'order',
name: 'Order',
fields: [...],
access: {
ownerPlane: 'user', // 'user' | 'project' | 'organization'
defaultVisibility: 'private', // 'private' | 'public'
},
}| Field | Value | Description |
|---|---|---|
ownerPlane | 'user' | Records are owned by a person: the one the write names as the owner, else the person who writes it. Each owner’s records are kept apart on the public API, cached privately, and looked up by owner. Required for a per-user singleton. |
'project' | No individual owner; records belong to the project, whoever creates them. A signed-in user’s create makes a record of the project’s, and its createdBy says who made it. The platform default. | |
'organization' | Records are owned by one of the project’s organizations, created by the project, never for a person, and written by the project or by the organization that owns them. Ownership, not containment: the rows stay in the project plane, so the project credential reads every organization’s. A project can declare it before it has any organization; see below. | |
defaultVisibility | 'private' | New records are visible only to the owner and explicit grants. The default, except on a project-owned model created without one, which starts 'public'. |
'public' | New records are readable by anyone through the project’s public API, including unauthenticated reads with a publishable key. |
The owner of a user-owned record is the user who creates it. A record written for a user (a guest’s order, a sale rung up at the till) names its owner instead: from an operation that declared records:attribute:<model>, or from the console and the CLI (--owner-id). The owner named must be a user of the project, inside the organization the request acts in. A project model’s records take no owner, so naming one there is refused. See Writing for a user from an operation.
A private record of a project model is read and changed by whoever acts as the project, which is the project:stand permission: a person on your team whose role gives it, a server or admin key that holds it, an operation that declares it. Anyone else reads one only where their grant reads every owner’s records (records:read.all). To give each user records of their own, make the model user-owned.
Omit access entirely for a project-owned model. On a model that already exists, leaving defaultVisibility out keeps the visibility it has, including one set in the console. Records’ per-record visibility and grants are managed at runtime from the console editor’s Access tab.
Changing defaultVisibility later re-applies to a model’s existing records when the change is published, in both directions: switch a model to public and its already-created records become readable; switch it back to private and they are hidden again. Records whose visibility you set individually from the Access tab are treated as deliberate and keep their setting, so a later change to the model default never overwrites them.
Organization-owned models
ownerPlane: 'organization' is for a product built on organizations: each record belongs to one of the project’s organizations — _ownerKind is "organization" and _ownerId is the organization’s id.
It is ownership, not containment. The row stays in the project plane (org_id unset), so a project credential with no organization claim reads every organization’s records — the same way it reads every user’s. That is the point: a multi-tenant app looks up the settings record for <sub>.theapp.com by natural key with its project key, reads _ownerId, and only then acts inside that organization (how).
Records are created by the project (a project credential, or a person on your team in the console), never for a user, and the organization that owns one may update and delete it while standing in itself, though the record stays in the project plane. The owner is named by ownerId on create, or by the organization the caller acts in (the console’s organization switcher, or the data API’s X-Org-Id header); if both are given they must agree. The owner must be an active organization of the project. Moving a record to another organization is a project-level act, from the record’s Access tab.
What is refused, and why:
- Creating a record while the project has no organizations:
FAILED_PRECONDITION. The model can be declared in the same push that sets up a fresh project, but a record needs an owner, and the error names the fix: create an organization (foir orgs create, or theCreateOrganizationRPC), then name it withownerIdor act inside it withX-Org-Id. With organizations present, naming none, or naming one that is not an active organization of the project, isINVALID_ARGUMENT. defaultVisibility: 'public'andcacheControl.scope: 'PUBLIC'— as on every owned plane: an organization-owned record is private to its owner, and its response-cache entries are isolated per owner.- A create acting for a user (a signed-in user, or an operation acting for one), or one naming a user as the owner: the record is the project’s to write, and an organization’s row has no user owner.
singleton: true on this plane means one record per organization, exactly as a user-plane singleton is one record per user — the shape of a per-tenant settings record.
Deleting an organization leaves its records owned by an organization that no longer exists, and that is equally true when the organization goes because an organization above it was deleted: a deletion covers the whole subtree, and each organization in it is removed in its own right. The records are in the project plane rather than inside any organization, so the purge does not reach them. Foir does not reassign or delete them; whether a later organization may reuse a natural key is your application’s decision.
Relationship-derived visibility
By default a reference between records is structural only — pointing at a record never grants any access to it. (If it did, adding a reference would be a privilege-escalation path: anyone who could create a record pointing at yours could read it.) Sometimes, though, a record should be readable by whoever can read a record it points at. A reference field opts into that with the association_read relationship kind — relationship-derived read visibility, or a “borrow”.
Example
A user owns their order (ownerPlane: 'user', private). Back-office staff work a fulfilment_list that references the order. You want the owning user to read the fulfilment list for their own order — without granting it explicitly each time, and without exposing anyone else’s. Declare the reference field’s relationship as association_read:
{
key: 'fulfilment_list',
name: 'Fulfilment list',
fields: [
{
key: 'order',
type: 'reference',
config: {
referenceTypes: ['order'],
relationship: { kind: 'association_read' }, // borrow the order's read
},
},
// ...
],
}Now a fulfilment_list record is readable by anyone who can read the order it references. The user reads their own order → they read its fulfilment list. Another user can’t read that order, so they can’t read its fulfilment list either.
What a borrow does — and doesn’t — grant
| Property | Behaviour |
|---|---|
| Read only | A borrow confers read and nothing else — never write or delete on the referring record. |
| Opt-in per edge | Only a field declared association_read borrows. A plain association (the default) borrows nothing; the structural-only stance still holds for every other reference. |
| One hop | The borrow does not chain. If A borrows from B and B borrows from C, being able to read C does not let you read A. Each declared edge grants exactly the one read it names. |
| Direction | The referring record (the one holding the field) borrows from the referenced record. Reading the target grants reading the holder — not the reverse. |
Relationship kinds
relationship.kind on a reference field selects how the edge behaves:
| Kind | Access conferred | Lifecycle |
|---|---|---|
association (default) | None — structural only | Target keeps its own access + lifecycle |
association_read | Borrows the referenced record’s read | Target keeps its own access + lifecycle |
composition | Parent access cascades to the child (read and write) | Child is owned by the parent; deletes cascade |
hierarchy | None — structural only | The model’s tree edge. Target keeps its own access; deleting a parent clears the edge. See Hierarchy |
Why it’s opt-in. Relationships are structural by default precisely so that adding a reference can never silently widen who can see a record.
association_readmakes the access-bearing edge explicit and bounded: read-only, one hop, declared per field. Reach for it when the visibility genuinely derives from the relationship (a fulfilment list for an order, a line item on an invoice). For anything ad-hoc or one-off, issue an explicit per-record grant from the Access tab instead.
hierarchy is deliberately not access-bearing. A page nested under another page is a routing fact, not a permission one, and a tree that quietly shared grants downward would make every re-parent a security change. Use composition when you do mean ownership.
Real-World Example
From the Cloudflare KV Redirect extension — a redirect model with text, enum, integer, and date fields:
{
key: 'redirect',
name: 'Redirect',
fields: [
{ key: 'displayName', type: 'text', label: 'Display Name', required: false },
{ key: 'sourcePattern', type: 'text', label: 'Source Pattern', required: true },
{ key: 'targetPattern', type: 'text', label: 'Target Pattern', required: true },
{
key: 'statusCode',
type: 'enum',
label: 'Status Code',
required: true,
config: {
options: [
{ value: 'http301', label: '301 - Permanent Redirect' },
{ value: 'http302', label: '302 - Temporary Redirect' },
{ value: 'http307', label: '307 - Temporary Redirect (preserve method)' },
{ value: 'http308', label: '308 - Permanent Redirect (preserve method)' },
],
},
},
{ key: 'priority', type: 'integer', label: 'Priority', required: false },
{ key: 'activeFrom', type: 'date', label: 'Active From', required: false },
{ key: 'activeTo', type: 'date', label: 'Active Until', required: false },
{
key: 'reason',
type: 'enum',
label: 'Reason',
required: false,
config: {
options: [
{ value: 'migration', label: 'Site Migration' },
{ value: 'rebrand', label: 'Rebrand / Rename' },
{ value: 'campaign', label: 'Marketing Campaign' },
{ value: 'discontinued', label: 'Discontinued Content' },
{ value: 'seo', label: 'SEO Optimization' },
{ value: 'other', label: 'Other' },
],
},
},
],
}Next Steps
- Configuration Reference — Full API reference
- Defining Operations — Add operations to process model data
- Defining Hooks — Trigger actions on model lifecycle events
- Field Types — Detailed field type documentation