Rayfin

Querying

Read Rayfin entities with the type-safe select/where/orderBy/execute chain — filtering, sorting, relationship paths, cursor pagination, and result types that match your selection.

client.data.<Entity> is a fluent, typed query builder for every entity in your schema. It compiles to GraphQL against Data API Builder — you never write a query string by hand.

Set up the client

Every example below uses the shared rayfinClient — see Set up the client for how to create it once with dataService<AppSchema>() and reuse it.

The query chain

Build a query by chaining .select(), then optionally .where() and .orderBy(), then call .execute():

const todos = await rayfinClient.data.Todo.select([
  'id',
  'title',
  'isCompleted',
  'createdAt',
])
  .where({ isCompleted: { eq: false } })
  .orderBy({ createdAt: 'desc' })
  .execute();

List every field your code reads in .select() — the result contains only those fields, and a query without .select() returns only id. .where() and .orderBy() are optional and can be omitted or reordered relative to each other, but .execute() (or .executePaginated(), see Pagination) always comes last.

.select() returns a new builder that carries over the filters, ordering, and page size set so far. Chain from the builder it returns, or keep it in a variable — calling .select() and ignoring its result leaves the original builder's selection unchanged. Changed in 2.0

const unfinished = rayfinClient.data.Todo.where({ isCompleted: { eq: false } });
const rows = await unfinished.select(['id', 'title']).execute();

Warning

.execute() returns a single page — 100 records by default — and does not tell you whether more records exist. A list that grows past one page is silently truncated. Use .execute() only for queries you know are bounded (a lookup table, a filter that can match only a handful of rows). For anything unbounded — a user's notes, an order history — use pagination instead.

Result types follow your selection

Changed in 2.0

A query's result type contains exactly the fields you select, so reading a field you did not select is a compile-time error rather than an undefined at runtime:

const todo = await rayfinClient.data.Todo.select(['id', 'title'])
  .where({ id: { eq: todoId } })
  .findFirst();

todo?.title;       // string
todo?.isCompleted; // type error: isCompleted was not selected
  • Pass the fields as a literal array to get exact types. If the field list is a widened or computed array, every field it could contain becomes optional, because the compiler cannot know which entries are present at runtime.
  • A selected @date() field is typed Date | string, and a @boolean() field boolean | 'true' | 'false', because responses can carry the wire string and the client does not infer a type from a string's contents. Convert explicitly — new Date(value), or value === true || value === 'true' — before you call date methods or rely on truthiness.
  • An optional field can be null at runtime even though its ? property only models undefined; check it with == null or ??.
  • The selection survives .where(), .orderBy(), .first(), and .after() in any order, and shapes what .execute(), .executePaginated(), and .findFirst() return.

In 1.x, a query was typed as returning the full entity even when the server returned fewer fields — without .select() the client already requested only id. 2.0 makes the types match the response, so code that read unselected fields now fails to compile. Add the fields to .select() to fix it.

Fetch a single record

To read fields of one record by its id, select them and call .findFirst(), which returns the first matching row or null:

const todo = await rayfinClient.data.Todo.select(['id', 'title', 'isCompleted'])
  .where({ id: { eq: '00000000-0000-0000-0000-000000000000' } })
  .findFirst();

if (!todo) {
  throw new Error('Todo not found');
}

The entity-level shortcuts findById(id), findFirst(filter), and findMany(filter) return only the primary key ({ id: string }), so use them to check whether a record exists or to collect ids — not to read other fields. findMany returns a single page, like .execute(). Use findById — findByPk does not exist. Changed in 2.0

const exists = (await rayfinClient.data.Todo.findById(todoId)) !== null;

const completedIds = (
  await rayfinClient.data.Todo.findMany({ isCompleted: { eq: true } })
).map((todo) => todo.id);

Filter with .where()

.where() takes an object keyed by field name. A bare value is shorthand for eq; an operator object is more explicit and required for anything other than equality.

.where({ isCompleted: { eq: true } })

Operators by field type

Field typeAvailable operators
@text() / @email()eq, neq, gt, gte, lt, lte, contains, notContains, startsWith, endsWith, isNull, in
@int() / @decimal()eq, neq, gt, gte, lt, lte, isNull, in
@boolean()eq, neq, isNull, in
@date()eq, neq, gt, gte, lt, lte, isNull, in

Combine conditions

Multiple keys in one .where() object are implicitly ANDed. Use explicit and / or arrays to combine or nest conditions:

.where({
  or: [
    { title: { contains: 'urgent' } },
    { isCompleted: { eq: false } },
  ],
})

Filter by foreign key, not by dot-path

Filter relationships by their {property}_id foreign key column, not by a dot-path into the related entity:

.where({ notebook_id: { eq: notebookId } })   // correct
.where({ 'notebook.id': { eq: notebookId } })  // wrong — dot-paths are select-only

To find rows with no related record, filter the declared foreign key with isNull:

.where({ notebook_id: { isNull: true } })

You can also write .where({ notebook: { isNull: true } }) on an optional relationship. The client turns it into the notebook_id check only when the same query selects a field from that relationship, such as 'notebook.name'.

Select nested fields with dot-paths

Changed in 2.0

Dot-paths are for .select() only — use them to pull fields off a related entity into the same result row. Follow a @one() relationship with a dot:

const notes = await rayfinClient.data.Note.select([
  'id',
  'title',
  'notebook_id',
  'notebook.id',
  'notebook.name',
])
  .orderBy({ createdAt: 'desc' })
  .execute();

notes[0].notebook?.name; // notebook is narrowed to { id, name }

Follow a @many() relationship with the [] marker. The client requests the relationship's items connection and returns an array that holds only the selected fields on each element:

const notebooks = await rayfinClient.data.Notebook.select([
  'id',
  'name',
  'notes[].id',
  'notes[].title',
]).execute();

notebooks[0].notes?.map((note) => note.title);
  • Each path follows exactly one relationship to one scalar field. notebook.name works, but notebook.owner.email (a third level) does not.
  • Select at least one field under a relationship — a bare relationship name such as 'notebook' is a type error.
  • Cardinality comes from the marker, not from the relationship's name: use [] for every @many() relationship and a plain dot for every @one(), whatever the property is called.
  • The client validates paths before it sends the request. A malformed path, or one relationship selected both with and without [], throws an error.

When you upgrade from 1.x, add [] to every collection path — 'notes.title' becomes 'notes[].title'. The type checker flags the old form and suggests the new one. Object paths such as 'notebook.name' are unchanged.

Sort with .orderBy()

Sort directions are the lowercase strings 'asc' and 'desc' — not capitalized constants:

.orderBy({ createdAt: 'desc' })

Paginate large lists

Because .execute() returns only one page and gives no signal that more records exist, use .first(n) with .executePaginated() for any query that can grow past a single page.

Fetch one page

const page = await rayfinClient.data.Note.select(['id', 'title', 'createdAt'])
  .orderBy({ createdAt: 'desc' })
  .first(25)
  .executePaginated();

page.items;       // up to 25 records
page.hasNextPage; // true if more records remain
page.endCursor;   // pass to .after() to fetch the next page

Fetch the next page

if (page.hasNextPage && page.endCursor) {
  const nextPage = await rayfinClient.data.Note.select(['id', 'title', 'createdAt'])
    .orderBy({ createdAt: 'desc' })
    .first(25)
    .after(page.endCursor)
    .executePaginated();
}

Keep .select(), .where(), and .orderBy() identical across every page in a sequence — a stable sort order is required for the cursor to advance correctly.

Fetch every record

Reuse one query and pass each page's endCursor to .after() until hasNextPage is false. The returned array is typed from the selection:

src/services/notes.ts
import { rayfinClient } from './rayfinClient';

export async function fetchAllNotes() {
  const query = rayfinClient.data.Note.select(['id', 'title', 'createdAt'])
    .orderBy({ createdAt: 'desc' })
    .first(100);

  let page = await query.executePaginated();
  const all = [...page.items];

  while (page.hasNextPage && page.endCursor) {
    page = await query.after(page.endCursor).executePaginated();
    all.push(...page.items);
  }

  return all;
}

Note

.first(n) is bounded by Data API Builder's maximum page size of 100,000. .first(-1) requests an unbounded page and still hits that same cap, so it only works when the full result set fits under it. For anything that might not, page through results with .after() instead of requesting everything in one large .first(n).

PagedResult also exposes a totalCount field, but Data API Builder does not populate it on paginated queries — do not rely on it.

Counting records

There is no count() on the fluent query chain. What exists is aggregation — count is one of five operations available through groupBy() and aggregate():

const [totals] = await rayfinClient.data.Order
  .where({ status: { eq: 'open' } })
  .aggregate({ open: { count: 'amount' } })
  .execute();

totals.aggregations.open; // number

Important

count aggregates numeric values, not rows. Data API Builder types every aggregation's field argument as the entity's numeric fields, so you can only count a numeric column — and the number it returns is the count of rows where that column is non-null.

That makes count a true row count only when you point it at a non-nullable numeric column. For an entity that has none — a Todo with a uuid id and text title, say — fall back to counting client-side:

const openTodos = await rayfinClient.data.Todo.select(['id'])
  .where({ isCompleted: { eq: false } })
  .execute();

const openCount = openTodos.length; // only correct if the result fits in one page

For a count that might exceed one page, page through with .executePaginated() and sum page.items.length across pages, since .execute() truncates and totalCount is not populated.

PromptAdd a paginated list query
In my Rayfin project, write a function that fetches all Todo records for the current user's "Archive" view using the RayfinClient. Select id, title, isCompleted, and createdAt, filter to isCompleted: { eq: true }, order by createdAt descending, and page through with .first(50) and .executePaginated(), passing each page's endCursor to .after() until hasNextPage is false, and return the combined list. Rayfin 2.0 types createdAt as Date | string in query results, so convert it with new Date(...) before using date methods.
PromptRead one record with the fields I need
In my Rayfin 2.0 project, find every place that calls findById, findFirst(filter), or findMany(filter) on client.data and then reads a field other than id. Replace each one with .select([...]) listing the fields the code reads, .where({ id: { eq: id } }) (or the original filter), and .findFirst() or .execute(). Keep using the builder that .select() returns, add the [] marker to any one-to-many selection path (for example 'notes[].title'), and run the type-checker until it passes.
Something wrong on this page?Report an issueEdit this page

On this page