@microsoft/rayfin-data package

Classes

AggregationNotSupportedError

Thrown when an aggregation query (groupBy/aggregate) is executed against a Data API Builder (DAB) endpoint that does not expose aggregation.

This happens when the Rayfin host has not enabled GraphQL aggregation (runtime.graphql.enable-aggregation) — for example when the service predates the aggregation change. In that case DAB omits groupBy from each entity's <Entity>Connection type and rejects the query at schema-validation time with a message that wraps the field and type names in backticks, for example: The field groupBy does not exist on the type <Entity>Connection.

Catch this error to detect a host that does not support aggregation and fall back or surface guidance to the user.

DataApi

Data-specific operations client for interacting with Data API Builder GraphQL endpoints.

Use the createDataApi factory function to create instances instead of instantiating directly.

GraphQLAggregationBuilder

Fluent builder for a Data API Builder (DAB) groupBy aggregation query.

Instances are returned from GraphQLQueryBuilder.groupBy or GraphQLQueryBuilder.aggregate. The generated GraphQL contains only a groupBy selection and never emits items, endCursor, or hasNextPage, because DAB rejects a query that combines groupBy with items.

Example

const rows = await client.data.Order
  .where({ status: { eq: 'shipped' } })
  .groupBy(['region'])
  .aggregate({
    revenue: { sum: 'amount' },
    orders:  { count: 'quantity' },
  })
  .execute();
GraphQLClient

GraphQL client for executing raw queries and mutations against a Data API Builder endpoint.

Prefer the fluent entity API (dataApi.<Entity>) for typical access; use this client when you need to send a hand-written GraphQL document.

GraphQLEntityClient

Type-safe fluent client for reading and mutating a single Data API Builder entity. Instances are typically obtained via the DataApi proxy (dataApi.<Entity>) rather than constructed directly.

Query methods (select, where, orderBy, first) return a chainable GraphQLQueryBuilder; call .execute() to run the query. Direct methods (findMany, findFirst, findById) and mutation methods (create, update, delete, upsert) execute immediately.

Example

const users = await dataApi.User
  .select(['id', 'name', 'email'])
  .where({ isActive: { eq: true } })
  .orderBy({ createdAt: 'desc' })
  .execute();

const created = await dataApi.User.create({ name: 'Jane', email: 'jane@example.com' });
GraphQLQueryBuilder

Fluent GraphQL query builder for constructing and executing complex queries.

ResponseHandler

Utilities for unwrapping Data API Builder (DAB) GraphQL response envelopes.

Interfaces

AggregationFieldOptions

Options object for a single aggregation operation.

AggregationOps

All valid aggregation operation entries for an entity, before the exactly-one-key constraint is applied.

All operations (sum/avg/min/max/count) accept only numeric fields: Data API Builder generates every aggregation's field argument as the <Entity>NumericAggregateFields enum, and count is documented as "count of numeric values". Non-numeric fields (for example a uuid id or a text column) are rejected by the server.

BooleanFilterInput

Comparison operators for filtering boolean fields (DAB-compliant).

DateFilterInput

Comparison operators for filtering date fields.

WARNING: DAB currently does not support comparison operators for Date fields in PostgreSQL.

GenericFilterInput

Fallback equality operators for fields without a specialized filter type.

GraphQLRequest

GraphQL request payload.

GraphQLResponse

GraphQL response payload.

GroupedAggregationRow

Result shape of a grouped aggregation query.

GroupedAggregationStage

The grouped-aggregation stage returned by GraphQLQueryBuilder.groupBy.

This stage exists to thread the concrete tuple of grouped keys (TGroup) through the fluent chain. groupBy captures the exact literal keys, and this interface carries them into GroupedAggregationStage.aggregate's result type so each grouped row's fields is typed to only the grouped columns (Pick<Entity, TGroup[number]>) instead of every scalar field.

Only where and aggregate are exposed: the row-shaping methods (select/orderBy/first/after) are intentionally absent because Data API Builder rejects a query that combines groupBy with row selection. Those combinations are therefore compile-time errors on this stage rather than runtime throws.

NumberFilterInput

Comparison operators for filtering numeric fields (DAB-compliant).

PagedResult

Forward-pagination result wrapper returned by executePaginated().

PaginationConfig

DAB pagination configuration (forward pagination only).

Microsoft Data API Builder only supports forward pagination with first and after. Backward pagination with last and before is not supported.

See https://learn.microsoft.com/en-us/azure/data-api-builder/keywords/after-graphql See https://learn.microsoft.com/en-us/azure/data-api-builder/keywords/first-graphql

StringFilterInput

Comparison operators for filtering string fields (DAB-compliant).

Type Aliases

AggregationEntry

A single aggregation-spec entry: exactly one operation with its value.

AggregationOpName

The five aggregation operation names supported by DAB.

AggregationOpValue

Shorthand-or-options value for an aggregation operation.

AggregationResult

Result type for a single aggregation entry.

count aggregations are non-nullable number; sum/avg/min/max are number | null because DAB emits them as nullable and SQL returns NULL over empty or all-null groups.

AggregationSpec

The full aggregation specification: a map of Builder-chosen aliases to single-operation entries.

CertainSelectionFields

Selection entries typed as a single field literal, so the field is known to be selected.

CleanEntityKeys

Clean entity keys that exclude prototype methods and functions

ComputedMutationInput

Mutation input written with computed property names, such as { [field]: value }, whose keys TypeScript cannot list. The input is accepted when its literal keys exist on TShape and its relationship values include their key. Because the computed keys are unknown, the mutation result is typed from TShape instead of the input.

CreateInput

Input type for creating new entities. The primary key field is optional since it's typically database-generated, but can be provided if the user wants to specify a particular id.

EligibleMutationValue

Input values that a create or update result echoes back: scalars (including null), Date, and relationship values that include their key. Arrays, undefined, any, unknown, and other objects resolve to never.

EntitySchema

Base entity schema type for the client.

ExactSelectionResult

Result shape when every selected field is a known literal: the selected scalar fields plus each selected relationship, narrowed to its nested fields.

ExactlyOne

A discriminated union that enforces exactly one key from All.

Each variant requires one key and marks all other keys as ?: never, so fresh object literals that specify more than one operation are rejected at compile time.

FieldFilterInput

Field-specific filter operators per DAB specification

FieldSelection

Type-safe scalar and one-level relationship selection. Use relationship[].field for arrays and relationship.field for objects. Bare object roots and deeper object leaves are not selectable.

FilterInput

DAB-compliant filter input type

FilterValue

Filter value that can be a direct value, a filter input, or a relationship isNull filter

GraphQLResponseValue

Values returned by GraphQL without runtime field metadata.

Dates and booleans may arrive as strings and cannot be distinguished from text fields by inspecting their contents. Other scalar objects stay atomic.

IsRelationship

Detects if a type is a relationship (object with a primary key that's not a primitive wrapper).

IsUnion

Resolves to true when T is a union type, otherwise false.

MergeProjection

Combines guaranteed fields with fields that might also be selected. Fields only in TPossible are optional.

MergeProjectionValue

Merges one field's guaranteed projection with nested fields that might also be selected. The possible extras are added as optional fields.

MutationInput

Transforms an entity type for mutation input.

  • @one relationship fields become RelationshipInput<T> (accepts keyed full or projected objects, or id-only)
  • Arrays are accepted and serialized by the existing mutation runtime. Manage relationships via the FK on the "many" side instead.
  • Primitive fields remain unchanged
MutationInputValue

The mutation input type for one entity field. Relationship fields accept a keyed reference (see RelationshipInput) and cannot be set to null; other field types are unchanged.

MutationResponseValue

The result type of one mutated field value. Scalars and Date are unchanged, relationships become RelationshipResult, and arrays become optional projections.

MutationResult

Computes the entity fields returned by a create or update mutation.

DAB returns the primary key plus primitive input fields. Relationship inputs are returned as primary-key-only nested objects by the SDK. Non-Date, non-keyed objects are omitted. Arrays are serialized and selected by the runtime, but their response is not guaranteed by this result contract.

MutationResultKey

Fields of T that a mutation result includes because TInput supplies an eligible value for them (see EligibleMutationValue).

MutationResultValue

The result type of field K of entity T in a mutation result.

NestedFieldPath

Selectable scalar fields and one-level relationship paths. Collections require [], such as wheel[].name; objects use settings.name. Object fields always require a scalar sub-selection.

NestedSelectionKeys

Fields selected under the relationship TRoot, such as title for posts[].title.

NestedSelectionResult

The relationship fields of a selection result, each narrowed to the nested fields selected for it.

NestedSelectionRoots

Relationship names used as the root of nested selection paths, such as category in category.name or posts in posts[].title.

NoExtraKeys

Rejects mutation inputs with keys that TShape does not declare, or with relationship values that lack their key. Resolves to an empty tuple for a valid TInput; otherwise it adds a required never argument, so the call fails to compile.

NumericKeys

Numeric keys of an entity, used to constrain the field argument of sum, avg, min, and max aggregations.

OptionalProjectionValue

Recursively marks object fields optional while keeping scalar and array shapes. Used for fields a response might include but cannot guarantee.

OrderByInput

DAB order by input

PartiallyCertainSelectionResult

Result shape when some selection entries are single field literals and others are unions. Known fields are required and the rest are optional.

PrimaryKeyOnly

Describes the root entity's primary key result. Models without a declared key use the schema's implicit UUID id: string.

See RelationshipInput for usage in mutation input types

ProjectNestedElement

Narrows one related object to the selected keys TKeys, preserving null and undefined.

ProjectNestedValue

Narrows a relationship value to the selected keys TKeys, keeping its object or array shape (including readonly arrays), null, and undefined.

ProjectionSafeMembers

Custom members of a GraphQLQueryBuilder subclass that stay available on a RowQueryBuilder: the keys the subclass declares in a readonly projectionSafeMembers property, excluding built-in methods.

ProjectionScalar

Supported scalar values that must remain atomic during projection. Infer Node's Buffer from its constructor when available: referring directly to an absent ambient Buffer would widen browser projections to any.

RelationshipInput

Flexible input type for relationship fields in mutations.

Accepts either:

  • Full or projected entity object with a concrete primary key
  • Object with only the primary key field(s)

Example

// Option 1: Pass full object (current behavior)
await client.data.Todo.create({
  title: 'My Todo',
  category: { id: 'cat-123', name: 'Work', color: '#ff0000' },
});

// Option 2: Pass primary-key-only object (new ergonomic shorthand)
await client.data.Todo.create({
  title: 'My Todo',
  category: { id: 'cat-123' },
});
RelationshipInputBranch

The relationship input accepted for one related entity type T: its key plus any projected fields. Keys that belong only to other members of TAll are rejected.

RelationshipIsNullFilter

DAB-compliant filter input

RelationshipKeyField

The key field that identifies a related entity in relationship inputs and results: id when the entity declares it, otherwise Id.

RelationshipKeyOnly

A reference to a related entity that contains only its key, such as { id: 'cat-123' }.

RelationshipMembers

The members of T that are relationships (objects with an id or Id).

RelationshipProjection

An optional, recursively projected view of a related entity. Relationship inputs accept it so objects returned by a selection can be passed back; only the key is written.

RelationshipResult

How a relationship appears in a mutation result: an object containing only the related entity's key, returned as id.

RequiredKeyFields

Picks the key fields K of T as required, writable, non-null values.

RequiredMutationResultKey

The MutationResultKey fields that are always present in the result, because TInput supplies them as required, defined, eligible values.

RowBuilderMethod

Built-in GraphQLQueryBuilder methods that RowQueryBuilder retypes or hides. Listing one in projectionSafeMembers has no effect.

RowQueryBuilder

The row-query surface of GraphQLQueryBuilder: every capability except the aggregation entry points (aggregate/groupBy), with terminal results limited to the selected fields.

The chainable row methods (select/where/orderBy/first/after) return this same type rather than the full builder, so once a query is shaped for row retrieval it can never transition into an aggregation via a later .where(). This closes the widening that a this-returning where() would otherwise reintroduce, making select(...).where(...).aggregate(...) (and the first/after/orderBy variants) compile-time errors. Runtime guards in GraphQLQueryBuilder.aggregate still back this up for callers that bypass the types.

The terminals (execute, executePaginated, findFirst) resolve to TResult, so after select() they return only the selected fields.

Subclass members are hidden unless their keys are explicitly declared in readonly projectionSafeMembers. Only opt in members that never expose a builder or reset its result type, including via promises and overloads. Implement a projection-aware select() override for custom fluent methods.

Example

class LabeledQuery extends GraphQLQueryBuilder<Schema, 'Todo'> {
  declare readonly projectionSafeMembers: 'label';
  label(): string { return 'todos'; }
}
// select(...).label() remains available without widening selected rows.
ScalarKeys

Scalar keys of an entity — string, number, boolean, or Date.

Excludes relationship, array, and nested object fields, matching the <Entity>ScalarFields GraphQL enum that Data API Builder (DAB) generates for aggregation and grouping.

SelectionLeafKeys

Field names of T that can be selected directly by name: scalar fields and arrays of scalars. Relationship fields need a nested path instead.

SelectionResult

Computes the entity shape returned by a GraphQL field selection.

Scalar fields become a top-level Pick, while relationship paths produce nested objects or arrays containing only the requested relationship fields.

Simplify

Flattens an intersection into a single object type, so editor hovers show the resolved fields of a query or mutation result.

TypedDataClients

Type-safe data clients based on entity schema.

UncertainSelectionFields

Selection entries typed as a union of fields, so any one of them might be selected.

UncertainSelectionResult

Result shape when the selected fields are not known exactly, such as a selection typed as a widened array. Every field that might be selected is optional.

UnionKeys

Every key declared by any member of the union T.

UpdateInput

Input type for updating existing entities.

All fields are optional. Relationship fields accept keyed full or projected objects, or primary-key-only. Array inputs are accepted, but do not guarantee returned relationship fields.

Example

// Update with primary-key-only for relationship
const input: UpdateInput<Todo> = {
  title: 'Updated Title',
  category: { id: 'new-cat-id' },
};
WhereUniqueInput

Input type for uniquely identifying an entity. Uses the centralized PrimaryKeyField type alias.

Functions

createDataApi<TSchema>(ApiClient)

Create a type-safe DataApi instance for interacting with Data API Builder GraphQL endpoints.

Example

const dataApi = createDataApi<{
  User: User;
  Organization: Organization;
}>(apiClient);

// GraphQL fluent interface (direct entity access):
const activeUsers = await dataApi.User
  .select(['id', 'name', 'email'])
  .where({ isActive: { eq: true } })
  .orderBy({ createdAt: 'desc' })
  .execute();

// GraphQL mutations:
const newUser = await dataApi.User.create({
  email: 'user@example.com',
  name: 'Jane Doe'
});
dataService<TSchema>()

Register typed app-owned data on a composed Rayfin client. Reuses the existing GraphQL entity clients and their query and mutation semantics.

Example

services: { data: dataService<{ Todo: Todo }>() }
deserializeDabResponse<T>(readonly unknown[], EntityClass<T>)

Deep transform a DAB response into plain TypeScript objects.

Two modes:

  1. Structure-only (no entity argument, default). Walks arrays and objects and preserves Date instances, but never value-sniffs strings for booleans or dates. A @text() or @set('true', 'false') field is byte-identical on the wire to a @date() or @boolean() field — only the declared decorator type can disambiguate them, and that metadata is not available here. Callers that need a Date or boolean from a known column must convert explicitly (e.g. new Date(row.createdAt) or deserializeBoolean(row.isActive)).

  2. Metadata-aware (with an entity class argument). Uses the decorated entity metadata to convert only @date() strings to Date instances and @boolean() strings to booleans. Fields declared as @text(), @set(), etc. remain strings even when their contents look like dates. Relationship fields recurse with the target entity's metadata. Invalid date strings on a @date() field are preserved as strings rather than becoming Invalid Date.

Invalid ISO strings on a @date() field are preserved as strings rather than becoming Invalid Date; callers should defend against untrusted wire data since the declared type still says Date.

deserializeDabResponse<T>(unknown, EntityClass<T>)
deserializeDabResponse<T>(unknown)
formatGraphQLValue(any)

Formats a value for inline use in a GraphQL query string. Applies proper escaping for strings (backslash, quote, newline, carriage return, tab).

Function Details

createDataApi<TSchema>(ApiClient)

Create a type-safe DataApi instance for interacting with Data API Builder GraphQL endpoints.

Example

const dataApi = createDataApi<{
  User: User;
  Organization: Organization;
}>(apiClient);

// GraphQL fluent interface (direct entity access):
const activeUsers = await dataApi.User
  .select(['id', 'name', 'email'])
  .where({ isActive: { eq: true } })
  .orderBy({ createdAt: 'desc' })
  .execute();

// GraphQL mutations:
const newUser = await dataApi.User.create({
  email: 'user@example.com',
  name: 'Jane Doe'
});
function createDataApi<TSchema>(apiClient: ApiClient): DataApi<TSchema> & TypedDataClients<TSchema>

Parameters

apiClient
ApiClient

The ApiClient instance for making HTTP requests

Returns

DataApi<TSchema> & TypedDataClients<TSchema>

A fully typed DataApi instance with direct entity access

dataService<TSchema>()

Register typed app-owned data on a composed Rayfin client. Reuses the existing GraphQL entity clients and their query and mutation semantics.

Example

services: { data: dataService<{ Todo: Todo }>() }
function dataService<TSchema>(): ClientServiceFactory<DataApi<TSchema> & TypedDataClients<TSchema>>

Returns

A factory for the client's typed data service.

deserializeDabResponse<T>(readonly unknown[], EntityClass<T>)

Deep transform a DAB response into plain TypeScript objects.

Two modes:

  1. Structure-only (no entity argument, default). Walks arrays and objects and preserves Date instances, but never value-sniffs strings for booleans or dates. A @text() or @set('true', 'false') field is byte-identical on the wire to a @date() or @boolean() field — only the declared decorator type can disambiguate them, and that metadata is not available here. Callers that need a Date or boolean from a known column must convert explicitly (e.g. new Date(row.createdAt) or deserializeBoolean(row.isActive)).

  2. Metadata-aware (with an entity class argument). Uses the decorated entity metadata to convert only @date() strings to Date instances and @boolean() strings to booleans. Fields declared as @text(), @set(), etc. remain strings even when their contents look like dates. Relationship fields recurse with the target entity's metadata. Invalid date strings on a @date() field are preserved as strings rather than becoming Invalid Date.

Invalid ISO strings on a @date() field are preserved as strings rather than becoming Invalid Date; callers should defend against untrusted wire data since the declared type still says Date.

function deserializeDabResponse<T>(data: readonly unknown[], entity: EntityClass<T>): T[]

Parameters

data

readonly unknown[]

The DAB response payload (row, list of rows, or nested shape).

entity

EntityClass<T>

Optional decorated entity class produced by @entity(). When provided, the returned value matches the declared TypeScript types of the entity (e.g. @date() createdAt: Date is a real Date).

Returns

T[]

deserializeDabResponse<T>(unknown, EntityClass<T>)

function deserializeDabResponse<T>(data: unknown, entity: EntityClass<T>): T

Parameters

data

unknown

entity

EntityClass<T>

Returns

T

deserializeDabResponse<T>(unknown)

function deserializeDabResponse<T>(data: unknown): T

Parameters

data

unknown

Returns

T

formatGraphQLValue(any)

Formats a value for inline use in a GraphQL query string. Applies proper escaping for strings (backslash, quote, newline, carriage return, tab).

function formatGraphQLValue(value: any): string

Parameters

value

any

Returns

string