Skip to content

ResourceBuilder

Defined in: packages/schema/src/resource.ts:58

A resource as resource(name) builds it. Every method returns a new builder, so a resource is one chain. See resource().

F extends FieldsInput = { }

K = never

N extends string = string

readonly $fields: F

Defined in: packages/schema/src/resource.ts:62

The fields, for the compiler only, which InferRecord reads; never set.


readonly $key: K

Defined in: packages/schema/src/resource.ts:64

The fields of the key, for the compiler only, which RecordKey reads; never set.


readonly $name: N

Defined in: packages/schema/src/resource.ts:60

The name, for the compiler only, which typed layouts read to know a resource by its name; never set.

access(rules): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:411

Rules per operation (list, read, create, update, delete). A rule returns true, false, or a filter that limits the rows. An operation without a rule needs its capability when the app has roles. See Access.

Access<F>

ResourceBuilder<F, K, N>

.access({
read: roles.can('work_orders.read'),
update: roles.can('work_orders.update').and((_ctx, record) => (record as { status: string }).status !== 'done'),
delete: roles.is('admin'),
})

author(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:212

The field holding the id of the user who created the record, such as a chat message’s sender: every create sets it to the signed-in user’s id, and no request may write it, so it is never the client’s word. A create by no user leaves it empty.

(r) => Ref

ResourceBuilder<F, K, N>

.author((r) => r.author_id)

bucketsOf<S, B, M>(source, spec): ResourceBuilder<BucketFields<S, B, M>, Ref<"id", string>, N>

Defined in: packages/schema/src/resource.ts:107

Makes it a time rollup of source: one row per hour or day, in UTC, of time, and per value of the by fields, with the count of records as events and each measure as <field>_sum or <field>_max. Sets the fields, the key id and the source’s tenant; protobase migration writes its table, indexes and refresh function. Only the database writes its rows. See Time rollups.

S extends FieldsInput

B extends readonly Ref[]

M extends BucketMeasuresInput<S> = { }

ResourceBuilder<S, unknown>

BucketsSpec<S, B, M>

ResourceBuilder<BucketFields<S, B, M>, Ref<"id", string>, N>

resource('readings_hourly').table('readings_hourly').bucketsOf(readings, {
time: (r) => r.taken_at, every: 'hour', by: (r) => [r.device_id], measures: { watts: ['sum', 'max'] }, late: '2 hours',
})

checks(checks): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:178

The database checks whose refusal the API names, by constraint name: a CHECK constraint, or a trigger’s raise exception ... using errcode = 'check_violation', constraint = '<name>'. A write one refuses is a 400 invalid-record whose error has the name as its code and the label as its message, never the database’s own text; the admin app shows the label, translated as resources.<resource>.checks.<name>.label, with {field} values from the record. A name is declared once across the app. See Checks the database makes.

Record<string, CheckModel>

ResourceBuilder<F, K, N>

.checks({ tasks_parked_by_hand: { label: '{title} waits for a day, so it stays parked.' } })

comments(): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:306

Lets the people who may read a record comment on it, and mention others who may read it too, who get an email. The record page shows the thread with l.comments(), and admins list every comment as Comments. See Record comments.

ResourceBuilder<F, K, N>


derived(name, spec): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:338

A value worked out from other records for each of its records, which Protobase keeps current: it records what the compute function, the default export of derived/<resource>.<name>.ts, read, and runs it again when a change touches that or a time check flips. into is the read-only field it goes into, or a field of another resource’s record of the same key; job is enqueued each time the value changes. reads names the other resources it may read. See Derived values.

string

DerivedSpec<F>

ResourceBuilder<F, K, N>

.derived('verdict', { into: (r) => r.verdict, reads: ['tasks'] })

etagFrom(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:358

The read-only field whose change makes a record’s new ETag, for a table whose version column does not change on every write: one every record has, and not a sensitive one. Without it a version column is used, then updated_at, then a hash of the row.

(r) => Ref

ResourceBuilder<F, K, N>


eventMatches(): Record<string, EventMatch<any>>

Defined in: packages/schema/src/resource.ts:363

The code predicates (match) of its events, by event name.

Record<string, EventMatch<any>>


events(define): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:282

The events changes to its records raise, captured in the database for every write, from the API or elsewhere. See Declaring events.

(e, r) => EventSpec[]

ResourceBuilder<F, K, N>

.events((e, r) => [
...e.crud(),
e.becomes('large', 'total > 1000'),
e.updated('statusChanged', { changed: [r.status] }),
e.updated('reopened', { from: 'status = "cancelled"', when: 'status != "cancelled"' }),
])

explicitGrants(): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:349

Leaves it out of role wildcards over resources such as *.read: with roles, only * itself and capabilities that name it, such as webhook_subscriptions.read, grant it. For resources whose records hold secrets, which a role written as “read everything” should not reach. See Resources that need named grants.

ResourceBuilder<F, K, N>


fieldAccess(): Record<string, FieldAccess>

Defined in: packages/schema/src/resource.ts:437

Role-based rules per field, for fields that declared .access(...).

Record<string, FieldAccess>


fields<N>(fields): ResourceBuilder<N, never, N>

Defined in: packages/schema/src/resource.ts:89

The columns, by field name, each built with f. name: null ignores a column on purpose. The column is the snake_case of the name unless .column() says otherwise. Required, and called before the methods that pick fields.

N extends FieldsInput

N

ResourceBuilder<N, never, N>


history(options?): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:297

Keeps every change of its records, from the API or elsewhere: the fields before and after, and who made it. The record page shows it as History, and admins list every change as Activity. See Record history. ignore names fields whose changes are not captured at all, such as counts the database keeps: an update of only those keeps nothing, and no change holds them.

readonly keyof ActiveFields<F> & string[]

ResourceBuilder<F, K, N>

.history({ ignore: ['tasks_done', 'progress'] })

ignoredColumns(): string[]

Defined in: packages/schema/src/resource.ts:459

The columns of the fields given as null, which the resource ignores on purpose.

string[]


links(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:263

Declares the resource’s records links between two others, such as tasks and the objectives they serve, so a record of either side lists the other’s records, and those that point at them, at /{parent}/{key}/{resource}. Both are filterable relations of one column. A list still reads as itself: a task’s address stays /tasks/{key}.

(r) => readonly [Ref, Ref]

ResourceBuilder<F, K, N>

.links((r) => [r.objective_id, r.task_id])

live(spec?): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:322

Refreshes the pages open on its records and lists as soon as they change, from the API or elsewhere: the server tells each open app which records changed, never their values, and the app reads them again as its user. See Live updates. reads names the resources whose changes refresh it in place of its own, for one backed by a database view, which takes no trigger: see Resources backed by a view.

string[]

ResourceBuilder<F, K, N>

.live({ reads: ['messages', 'replies'] })

openExisting(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:198

A unique key of the table, as its fields, whose conflict on create opens the record already holding those values: the API’s 409 names that record’s key (existing.key) to a caller who may read it, and the create form opens it. The fields must be exactly the columns of a unique index or constraint, such as one over a generated column. See Opening an existing record.

(r) => Ref[]

ResourceBuilder<F, K, N>

.openExisting((r) => [r.organization_id, r.member_key])

owner(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:183

The field holding the owning user’s id, which .own capability scopes filter on.

(r) => Ref

ResourceBuilder<F, K, N>


parent(pick, access): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:248

A relation whose record each record belongs to, and the access on it writing them needs: creating a record, changing it (the parent it leaves and the one it moves to), deleting and undeleting it all need access on the parent, checked with the caller’s own access rules on its resource and locked until the write commits. With read, every read of its records (lists, counts, aggregates, gets and labels) also keeps to those whose parent the caller reads there. A null relation checks nothing; each call adds a check. See Records that belong to another.

(r) => Ref

ParentAccess

ResourceBuilder<F, K, N>

.parent((r) => r.vm_id, 'update')

position(pick, o?): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:230

The integer field holding the records’ order, 1 the first, which a list’s Reorder button changes by dragging the records; a move renumbers them 1, 2, 3, … in one batch reorder. With within, a relation, each parent’s records have an order of their own, as an invoice’s items do, sorted in the parent’s related section. The field must be sortable and within filterable. With after, a record never ranks above the records it depends on through a join resource (see PositionAfterModel), which reorder checks. See Reordering by hand.

(r) => Ref

PositionAfterModel

(r) => Ref

ResourceBuilder<F, K, N>

.position((r) => r.position, { within: (r) => r.invoice_id })
.position((r) => r.position, { after: { resource: 'task_dependencies', field: 'task_id', key: 'depends_on_id', while: 'status != "done"' } })

prepare(preparer): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:393

Fills in or rewrites the values of every create and update on the server before they are written, inside the write’s transaction, after the field checks and .validate() rules, which check what it returns again: it returns the values to write, and may set read-only fields, such as a generated key, which no request can. It throws a FieldIssue to refuse the write with 422 and the field named. It does database and CPU work only; work that waits on the network goes in a job a write hook enqueues. Each call adds one, run in order. See Preparing a record.

Preparer<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }>

ResourceBuilder<F, K, N>

.prepare((values, { operation }) => (operation === 'create' ? { ...values, token: crypto.randomUUID() } : values))

primaryKey<P>(pick): ResourceBuilder<F, P, N>

Defined in: packages/schema/src/resource.ts:125

The key: one field, or a list for a key of several columns ((r) => [r.order_id, r.line_no]). Required.

P extends KeyRefs

(r) => P

ResourceBuilder<F, P, N>


recordSchema(): ZodType<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }, unknown, $ZodTypeInternals<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }, unknown>>

Defined in: packages/schema/src/resource.ts:449

The Zod schema of a whole record, from its fields’ schemas.

ZodType<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }, unknown, $ZodTypeInternals<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }, unknown>>


reveals(reveals): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:427

Values revealed like sensitive fields, by name, but made when one is asked for instead of read from a column: a secret another service keeps, or a file of settings built from several. POST /{resource}/{key}:reveal with { "field": "<name>" } answers one for a caller who may read the record, after the same audit event as a field’s reveal. Each call adds names, which no field may have. See Computed reveals.

Record<string, ComputedReveal<RecordOf<F>>>

ResourceBuilder<F, K, N>

.reveals({ env: { value: (app) => secrets.envFile(app.id), read: roles.is('owner'), strongSignIn: { minutes: 15 } } })

search(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:158

Fields matched by search("...") and bare words in filters. Authoritative over the UI’s list search defaults. r.phone.digitsEnd() matches only the end of the field’s digits, for phone numbers.

(r) => SearchRef[]

ResourceBuilder<F, K, N>


softDelete(pick): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:141

A nullable timestamp or date that marks a record deleted: deleting sets it, lists leave such rows out and :undelete clears it.

(r) => Ref

ResourceBuilder<F, K, N>


table(table): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:81

The table, with or without its schema: 'shop.repairs' or 'repairs'. Required.

string

ResourceBuilder<F, K, N>


tenant(pick, options?): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:150

The field that separates tenants: every query is limited to the caller’s tenant, creates set it, and a request body may not. With across: 'memberships', its lists also read the other tenants the caller is a member of, each as the caller’s role there allows; see Lists across organizations.

(r) => Ref

TenantOptions = {}

ResourceBuilder<F, K, N>


toModel(): ResourceModel

Defined in: packages/schema/src/resource.ts:444

The resource as the server and the app read it. Throws when the table, fields or key are missing, or a field option conflicts with another.

ResourceModel


validate(validator): ResourceBuilder<F, K, N>

Defined in: packages/schema/src/resource.ts:376

A rule over the whole record, run after the field checks on every create and update. Its issues answer 400 with the field named. Each call adds a rule.

Validator<F>

ResourceBuilder<F, K, N>

.validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))