Creating, updating, deleting
Create, update, upsert, and delete Rayfin records through the type-safe client, set relationship fields correctly, and know what each mutation returns.
client.data.<Entity> also handles writes. create, update, upsert, and delete are
fully typed against your entity — including relationship fields defined with @one() — and a
field the entity does not declare is a compile-time error.
Create a record
Pass every required field. id is optional — omit it and the server generates a UUID.
const session = rayfinClient.auth.getSession();
if (!session.isAuthenticated || !session.user) {
throw new Error('Sign in before creating a todo.');
}
const todo = await rayfinClient.data.Todo.create({
title: 'Ship the changelog',
isCompleted: false,
createdAt: new Date(),
user_id: session.user.id,
});session.user.id is the subject id that row-level policies compare as claims.sub — see
Permissions. Supply your own id at creation time only if you
specifically need a client-generated identifier — it is validated as a UUID like any other
write.
What mutations return
A mutation returns the record's primary key plus the fields you sent — not the whole row:
| Operation | Returns |
|---|---|
create(input) | Primary key plus the scalar, Date, and relationship fields in input |
update(where, input) | Primary key plus the scalar, Date, and relationship fields in input |
delete(where) | Primary key only |
upsert(where, create, update) | The create result shape or the update result shape, depending on which branch ran |
todo.id; // string
todo.title; // string — it was in the input
todo.createdAt; // Date | string — returned values arrive as the wire sends them- A field you pass as optional, or as a value that may be
undefined, stays optional in the result. - A relationship you set comes back as an object holding only its key, such as
note.notebook.id. - Fields you did not send — server defaults, other columns — are not in the result. Read them
back with
.select([...]).where({ id: { eq: todo.id } }).findFirst()(see Fetch a single record). - Returned
@date()values are typedDate | stringand@boolean()valuesboolean | 'true' | 'false', as in query results — see Values you read back.
Update a record
update takes a filter identifying the record, then the fields to change. Only id is
supported in the filter.
const updated = await rayfinClient.data.Todo.update(
{ id: todo.id },
{ isCompleted: true },
);
updated.isCompleted; // boolean | 'true' | 'false'Send only the fields that changed — update does a partial patch, not a full replace.
Delete a record
const deleted = await rayfinClient.data.Todo.delete({ id: todo.id });
deleted.id; // the only field returneddelete resolves once the backend confirms the row is gone, and returns only its primary key.
Setting @one() relationships in mutations
For an entity with a @one() field (see Relationships), pass the
related object with its primary key — { id } alone, or a full or selected object that
includes id. The client writes only the key, into the entity's foreign key field
(notebook_id).
// @uuid({ optional: true }) notebook_id?: string;
// @one(() => Notebook, { optional: true }) notebook?: Notebook;// Pass the relationship object with only the primary key
const note = await rayfinClient.data.Note.create({
title: 'Meeting notes',
content: 'Discussion points…',
createdAt: new Date(),
user_id: session.user.id,
notebook: { id: notebookId },
});
note.notebook.id; // the key you passed
// Or pass an object you already selected — only its id is written
const work = await rayfinClient.data.Notebook.select(['id', 'name'])
.where({ name: { eq: 'Work' } })
.findFirst();
if (work) {
await rayfinClient.data.Note.create({
title: 'Weekly summary',
content: 'Use a selected object when you already have one',
createdAt: new Date(),
user_id: session.user.id,
notebook: work,
});
}The same rule applies to update:
// Move a note to a different notebook by passing only the target's id
await rayfinClient.data.Note.update(
{ id: note.id },
{ notebook: { id: newNotebookId } },
);When the entity declares the foreign key field, you can set it directly instead —
{ notebook_id: newNotebookId }. Pass either the relationship object or the foreign key, not
both: if you pass both for the same relationship, the client sends one foreign key value and
the relationship object wins. Changed in 2.0
Rules for relationship values
- A relationship value needs a concrete key. The client rejects a relationship object
whose
idisnullorundefinedbefore it sends the mutation. - A relationship value cannot be
null.notebook: nullis a type error; to leave an optional relationship unset, omit it. - Clearing a relationship goes through the foreign key. The client sends
{ notebook_id: null }as-is, but TypeScript accepts it only when the field's type in your schema includesnull— and a decorated entity property cannot be declared| null(see The nullable pattern). - Unknown fields fail to compile. A misspelled or undeclared field name in
create,update, or eitherupsertbranch is a type error.
@many() fields are the inverse side of a relationship. Do not pass them in a mutation — the
client does not turn an array into writes on the child rows. Manage that side from the child
records instead: set each child's notebook: { id } to reassign it, as shown above.
Full example
import { rayfinClient } from './rayfinClient';
export async function createTodo(title: string, userId: string) {
return rayfinClient.data.Todo.create({
title,
isCompleted: false,
createdAt: new Date(),
user_id: userId,
});
}
export async function completeTodo(id: string) {
return rayfinClient.data.Todo.update({ id }, { isCompleted: true });
}
export async function deleteTodo(id: string) {
await rayfinClient.data.Todo.delete({ id });
}Upsert
client.data.<Entity> also exposes upsert(where, create, update): it applies update
if a record matching where exists, or create otherwise. The result has the shape of the
branch that ran. Changed in 2.0
await rayfinClient.data.Category.upsert(
{ id: categoryId },
{ id: categoryId, name: 'Work' }, // used if no row with this id exists
{ name: 'Work' }, // used if it already exists
);In my Rayfin project, write a function in src/services/notes.ts that creates a new Note
using the RayfinClient. It should accept a title, content, and notebookId, set createdAt
to the current time, set user_id from the signed-in session
(rayfinClient.auth.getSession().user.id, throwing if no user is signed in), and assign the note
to its notebook by passing `notebook: { id: notebookId }`. In Rayfin 2.0, create returns only
the id plus the fields it was given, so if the caller needs any other field, read the note back
with .select([...]).where({ id: { eq: note.id } }).findFirst().