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().
Type Parameters
Section titled “Type Parameters”F extends FieldsInput = { }
K = never
N extends string = string
Properties
Section titled “Properties”$fields
Section titled “$fields”
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.
Methods
Section titled “Methods”access()
Section titled “access()”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.
Parameters
Section titled “Parameters”Access<F>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.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()
Section titled “author()”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.
Parameters
Section titled “Parameters”(r) => Ref
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.author((r) => r.author_id)bucketsOf()
Section titled “bucketsOf()”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.
Type Parameters
Section titled “Type Parameters”S extends FieldsInput
B extends readonly Ref[]
M extends BucketMeasuresInput<S> = { }
Parameters
Section titled “Parameters”source
Section titled “source”ResourceBuilder<S, unknown>
BucketsSpec<S, B, M>
Returns
Section titled “Returns”ResourceBuilder<BucketFields<S, B, M>, Ref<"id", string>, N>
Example
Section titled “Example”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()
Section titled “checks()”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.
Parameters
Section titled “Parameters”checks
Section titled “checks”Record<string, CheckModel>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.checks({ tasks_parked_by_hand: { label: '{title} waits for a day, so it stays parked.' } })comments()
Section titled “comments()”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.
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
derived()
Section titled “derived()”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.
Parameters
Section titled “Parameters”string
DerivedSpec<F>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.derived('verdict', { into: (r) => r.verdict, reads: ['tasks'] })etagFrom()
Section titled “etagFrom()”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.
Parameters
Section titled “Parameters”(r) => Ref
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
eventMatches()
Section titled “eventMatches()”eventMatches():
Record<string,EventMatch<any>>
Defined in: packages/schema/src/resource.ts:363
The code predicates (match) of its events, by event name.
Returns
Section titled “Returns”Record<string, EventMatch<any>>
events()
Section titled “events()”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.
Parameters
Section titled “Parameters”define
Section titled “define”(e, r) => EventSpec[]
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.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()
Section titled “explicitGrants()”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.
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
fieldAccess()
Section titled “fieldAccess()”fieldAccess():
Record<string,FieldAccess>
Defined in: packages/schema/src/resource.ts:437
Role-based rules per field, for fields that declared .access(...).
Returns
Section titled “Returns”Record<string, FieldAccess>
fields()
Section titled “fields()”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.
Type Parameters
Section titled “Type Parameters”N extends FieldsInput
Parameters
Section titled “Parameters”fields
Section titled “fields”N
Returns
Section titled “Returns”ResourceBuilder<N, never, N>
history()
Section titled “history()”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.
Parameters
Section titled “Parameters”options?
Section titled “options?”ignore?
Section titled “ignore?”readonly keyof ActiveFields<F> & string[]
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.history({ ignore: ['tasks_done', 'progress'] })ignoredColumns()
Section titled “ignoredColumns()”ignoredColumns():
string[]
Defined in: packages/schema/src/resource.ts:459
The columns of the fields given as null, which the resource ignores on purpose.
Returns
Section titled “Returns”string[]
links()
Section titled “links()”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}.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.links((r) => [r.objective_id, r.task_id])live()
Section titled “live()”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.
Parameters
Section titled “Parameters”reads?
Section titled “reads?”string[]
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.live({ reads: ['messages', 'replies'] })openExisting()
Section titled “openExisting()”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.
Parameters
Section titled “Parameters”(r) => Ref[]
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.openExisting((r) => [r.organization_id, r.member_key])owner()
Section titled “owner()”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.
Parameters
Section titled “Parameters”(r) => Ref
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
parent()
Section titled “parent()”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.
Parameters
Section titled “Parameters”(r) => Ref
access
Section titled “access”Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.parent((r) => r.vm_id, 'update')position()
Section titled “position()”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.
Parameters
Section titled “Parameters”(r) => Ref
after?
Section titled “after?”within?
Section titled “within?”(r) => Ref
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.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()
Section titled “prepare()”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.
Parameters
Section titled “Parameters”preparer
Section titled “preparer”Preparer<{ [K in string | number | symbol]: { [K in string | number | symbol]: ActiveFields<F>[K] extends Field<V> ? V : never }[K] }>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.prepare((values, { operation }) => (operation === 'create' ? { ...values, token: crypto.randomUUID() } : values))primaryKey()
Section titled “primaryKey()”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.
Type Parameters
Section titled “Type Parameters”P extends KeyRefs
Parameters
Section titled “Parameters”(r) => P
Returns
Section titled “Returns”ResourceBuilder<F, P, N>
recordSchema()
Section titled “recordSchema()”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.
Returns
Section titled “Returns”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()
Section titled “reveals()”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.
Parameters
Section titled “Parameters”reveals
Section titled “reveals”Record<string, ComputedReveal<RecordOf<F>>>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.reveals({ env: { value: (app) => secrets.envFile(app.id), read: roles.is('owner'), strongSignIn: { minutes: 15 } } })search()
Section titled “search()”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.
Parameters
Section titled “Parameters”(r) => SearchRef[]
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
softDelete()
Section titled “softDelete()”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.
Parameters
Section titled “Parameters”(r) => Ref
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
table()
Section titled “table()”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.
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
tenant()
Section titled “tenant()”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.
Parameters
Section titled “Parameters”(r) => Ref
options?
Section titled “options?”TenantOptions = {}
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
toModel()
Section titled “toModel()”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.
Returns
Section titled “Returns”validate()
Section titled “validate()”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.
Parameters
Section titled “Parameters”validator
Section titled “validator”Validator<F>
Returns
Section titled “Returns”ResourceBuilder<F, K, N>
Example
Section titled “Example”.validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))