Skip to content

@softr/sdk

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

record-mutations

219 linesSource

>-

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. Pass a zod schema straight to .validator; Start accepts it and types data from it.

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: 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). 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), 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).

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 })
await ds.update(updateProject, {
  id,
  data: { status: { id: project.fields.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.

What a write accepts

Each key of data accepts exactly what its field takes (see record-queries):

  • 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).
  • CHECKBOX takes a boolean. Dates take ISO strings, never Date instances.
  • ATTACHMENT takes { url }, optionally with filename, id and type.
  • A multi-entry field takes an array of the value.

References