@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
245 lines (180 loc) • 13.7 kB
Markdown
---
name: record-mutations
description: >-
Create, update and delete records with defineMutation, ds.create, ds.update
and ds.delete: the payload keyed by your own field names, what each field type
accepts, and the filter that keeps an update or a delete to the records the
visitor may read, with one mutation per role. Use when submitting a form,
saving an edit or deleting a record, or when a write fails or changes nothing.
Reads are record-queries.
metadata:
type: sub-skill
library: softr-sdk
library_version: 1.19.0
---
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
# Writing records
`ds` writes records to a Softr datasource, from the server only.
## Setup
```ts
import { createServerFn } from '@tanstack/react-start'
import { z } from 'zod'
import { defineMutation } from '@softr/sdk'
import { ds } from '@softr/sdk/server'
```
A write's input arrives from the client, so validate it with a zod schema. Pass the schema straight to `.validator`; Start accepts it and types `data` from it. A typed function such as `(data: T) => data` checks nothing.
## Declare the write
A mutation declares exactly one operation, and each of the three needs its own declaration. One datasource carries as many mutations as the app needs, alongside its queries. A create mutation only works with `ds.create`; hand it to `ds.update` and the call throws `action "createProject" is declared as create, not update`.
```ts
const createProject = defineMutation({
id: 'createProject',
datasourceId: '00000000-0000-0000-0000-000000000000',
operation: 'create',
fields: {
name: 'fZk3Qm9pLw2Xa1', // SINGLE_LINE_TEXT
status: 'Ru7bVx2cNq0Ed9', // SELECT, choice ids 'draft' | 'active' | 'archived'
dueDate: 'Xp2dLh6vKz9Fa3', // DATETIME
},
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
```
The declaration follows the same rules as a read, spelled out in [record-queries](../record-queries/SKILL.md): `id` reads like a name and is unique across the app, queries counted alongside mutations; `datasourceId` is the opaque UUID from the table's registration, never derived from its name; the keys of `fields` are names you choose and the values are opaque field ids; `permissions` declares who may run the mutation, from the same three choices, and the SDK enforces it; and the object is written inline, because passing it through a variable or a spread widens the field ids and the types stop checking.
The mutation's `fields` bound the write: `data` can only name them, and the returned record only carries them. A delete mutation declares no `fields`, and giving it some is a type error.
An update or a delete must not be open to visitors: its `permissions` must be `{ userGroupTypes: ['LOGGED_IN_USERS'] }`. A visitor who is not logged in must never change or remove a record, so naming `NON_LOGGED_IN_USERS` is rejected for these two operations. A create may stay open to visitors, for a sign-up or a contact form.
## Core Patterns
### Create a record
```ts
const NewProject = z.object({ name: z.string(), dueDate: z.string() })
const addProject = createServerFn({ method: 'POST' })
.validator(NewProject)
.handler(async ({ data }) =>
ds.create(createProject, {
data: { name: data.name, dueDate: data.dueDate, status: { id: 'draft' } },
}),
)
```
Returns the created record as `{ id, fields }`, with `fields` keyed by the mutation's names and holding the same value shapes a read returns. Every key in `data` is optional. A field left out, or written as `null`, gets the datasource's default.
### Update a record
```ts
const updateProject = defineMutation({
id: 'updateProject',
datasourceId: '00000000-0000-0000-0000-000000000000',
operation: 'update',
fields: { status: 'Ru7bVx2cNq0Ed9', dueDate: 'Xp2dLh6vKz9Fa3' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
const archiveProject = createServerFn({ method: 'POST' })
.validator(z.object({ id: z.string() }))
.handler(async ({ data }) =>
ds.update(updateProject, { id: data.id, data: { status: { id: 'archived' } } }),
)
```
The record id is its own option; keep it out of `data`. An empty `id` throws.
`update` writes the keys in `data` and leaves every other field alone, so a field you leave out is a field you are not writing. On an update, `null` clears the field, where on a create it reached the default. Returns the updated record.
### Delete a record
```ts
const deleteProject = defineMutation({
id: 'deleteProject',
datasourceId: '00000000-0000-0000-0000-000000000000',
operation: 'delete',
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
const removeProject = createServerFn({ method: 'POST' })
.validator(z.object({ id: z.string() }))
.handler(async ({ data }) => {
await ds.delete(deleteProject, { id: data.id })
})
```
Resolves to nothing. A record that cannot be deleted throws.
### Change only the records the visitor may read
When a role reads only some records of a table, it updates and deletes only those records. `permissions` decides who may run the mutation, not which record. The id comes from the browser, so it can name any record. Give the update and the delete the same `filter` and `filterFields` as the role's queries (see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records)). A record that the filter excludes throws `datasource update failed for action "<id>": record "<id>" not found`, and nothing is written. A missing record throws the same error, so the visitor cannot find out which ids exist. A create takes no filter: set its owner link on the server, from the Record ID that `context.user.properties` holds (see [current-user](../current-user/SKILL.md#fields-of-the-visitors-row-userproperties)), never from an argument.
```ts
// The same filter as `myBookings`, the query every client reads bookings with.
const cancelMyBooking = defineMutation({
id: 'cancelMyBooking',
datasourceId: '00000000-0000-0000-0000-000000000002',
operation: 'update',
fields: { status: 'Ru7bVx2cNq0Ed9' },
filterFields: { client: 'Pc8vNm3kTq6Wz2' },
filter: { client: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})
const cancelBooking = createServerFn({ method: 'POST' })
.validator(z.object({ id: z.string() }))
.handler(({ data }) => ds.update(cancelMyBooking, { id: data.id, data: { status: { id: 'cancelled' } } }))
```
A delete declares `filterFields` and `filter` the same way, with no `fields`.
An update cannot write a field that its filter compares with a user token, such as the owner. Otherwise a user could give the record to another user, and `defineMutation` throws when the module loads. Keep that field out of the update's `fields`. When a role must reassign records, such as staff, declare a separate mutation for it, with its own `customGroups` and without that filter.
A visitor who is signed out, or a user with no value for the token, changes nothing: the write throws "not found". Show the error as a missing record, with no retry.
A create into a table that belongs to the visitor through its parent, such as a message in a chat, reads the parent through its filtered query before `ds.create` (see [record-queries](../record-queries/SKILL.md#a-table-that-belongs-to-the-visitor-through-its-parent)).
### Write only what the form may change
The browser can send any key. The datasource accepts every field the mutation declares. A form that shows two fields can therefore set a third one the mutation declares.
Declare one mutation per form, with only the fields that form edits. A second form that edits other fields gets its own mutation.
Validate with a zod schema that lists exactly those fields. Then name each field in `data`. Never pass the input on whole, and never spread it. Set a field the visitor must not choose, such as the owner, a status or a price, on the server, from `context` or a constant.
```ts
// Wrong: the input goes in whole, so the browser decides every field the mutation declares.
const saveProfile = createServerFn({ method: 'POST' })
.validator((data: { id: string; name: string }) => data)
.handler(({ data }) => ds.update(updateProfile, { id: data.id, data }))
// Right: the schema lists the form's fields, and `data` names each one.
const ProfileForm = z.object({ id: z.string(), name: z.string(), bio: z.string() })
const saveProfile = createServerFn({ method: 'POST' })
.validator(ProfileForm)
.handler(({ data }) => ds.update(updateProfile, { id: data.id, data: { name: data.name, bio: data.bio } }))
```
The lint rules `@softr/write-require-validator` and `@softr/write-no-raw-input` warn about both mistakes.
### Only the roles that change a table
Often fewer roles change a table than read it. A mutation's `customGroups` names only the roles that may change the table, also when more roles read it. In a barber app, every client reads the free hours, but only barbers open or close them. A barber also changes only their own slots. The read of slots has no filter, because every client reads every slot, so the update filters on the slot's barber:
```ts
// `barber` links to Users. Only barbers run it, and only on their own slots.
const setMySlotOpen = defineMutation({
id: 'setMySlotOpen',
datasourceId: '00000000-0000-0000-0000-000000000004',
operation: 'update',
fields: { open: 'Wd5nKp2xRb8Tc3' },
filterFields: { barber: 'Jf3sLc7nVb1Qx5' },
filter: { barber: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000b'] },
})
```
A write can be narrower than the read, never wider: a role that reads only its own records never writes through a mutation without that filter.
### One mutation per role
When roles may write different fields, declare one update per role, each with its own `customGroups`, `fields` and `filter`. Pick the mutation on the server by `context.user.userGroupIds`. A role that may read some records but not change them has no mutation that admits it: its group is in no `customGroups` of an update or a delete.
### Edit an existing record
An edit form needs both halves: a `defineQuery` to load the record and a `defineMutation` to save it. They are separate declarations over the same table, so give both the fields the form touches, and read the loaded values off the query's names.
```ts
const projectDetail = defineQuery({
id: 'projectDetail',
datasourceId: '00000000-0000-0000-0000-000000000000',
fields: { status: 'Ru7bVx2cNq0Ed9', dueDate: 'Xp2dLh6vKz9Fa3' },
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})
const project = await ds.get(projectDetail, { id })
if (project === null) throw notFound()
const status = project.fields.status
await ds.update(updateProject, {
id,
data: { status: status === null ? null : { id: status.id } },
})
```
A read answers a SELECT as `{ id, label }` and a write takes `{ id }`, so pass the id through rather than the whole value.
### Show the edit before the loader re-runs
A list whose rows a drawer or an inline control edits keeps the saved values over the loader's rows until a fresh read replaces them. `useOverrides` holds them by record id:
```tsx
const overrides = useOverrides<Partial<Deal['fields']>>()
const rows = deals.map((deal) => ({ ...deal, fields: { ...deal.fields, ...overrides.of(deal.id) } }))
<DealsDrawer onSaved={overrides.onSaved} />
```
`onSaved(recordId, patch)` is what a drawer calls before the write and again with the old value if the write fails; `clear(recordId)` drops a record's patch once the page has reloaded it.
### Form dropdowns for linked record fields
A form select for a `LINKED_RECORD` field needs its options from the linked table, not from the record being edited. Query the linked table with its own `defineQuery` and `ds.list`; each result's `id` is what you pass to the write payload. See [record-queries](../record-queries/SKILL.md).
### What a write accepts
Each key of `data` accepts exactly what its field takes (see [record-queries](../record-queries/SKILL.md#typing)):
- SELECT and LINKED_RECORD take `{ id }`. Not a bare string, and not the `{ id, label }` a read returns; the label is display data and a write does not accept it. For a form select that should follow the field's choices in Studio, read them with `ds.choices` (see [record-queries](../record-queries/SKILL.md)).
- CHECKBOX takes a boolean. Dates take ISO strings, never `Date` instances.
- ATTACHMENT takes `{ url }`, optionally with `filename`, `id` and `type`: one object, or `null`, for a one-file field. A record's attachment and an uploaded file are both written as they are. [file-uploads](../file-uploads/SKILL.md#attachment-shapes-read-upload-and-write) sets the read, upload and write shapes side by side.
- A multi-entry field takes an array of the value.
## References
- [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the read half of an edit form, and the codegen the write types come from. Load it alongside this skill for any screen that shows a record before changing it.
- [record-queries/references/field-types.md](../record-queries/references/field-types.md): the value shape every field reads back as. Load it when you are unsure what a field accepts.
- [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor off `context`