Native GraphQL API
native.makeSchema serves a GraphQL API generated from your schema.cyphra and run by the
typed client: every root field is one client operation (findMany, findUnique, …),
compiled to one Cypher statement, so filters, ordering, paging, writes and errors behave the same from
TypeScript and from GraphQL. What the API exposes is configured in TypeScript, typed against the
generated client.
Experimental (see the stability policy): the native API
may change in a minor release. This release serves reads (findUnique, findFirst,
findMany, count), writes (create, createMany, update, updateMany, upsert,
delete, deleteMany, off by default) and auth (rules compiled into the statement,
field rules, authenticated). Nested update / delete / upsert, aggregates, search and
traversals come next (#77 ). Relay Node is
opt-in (below). To keep the API @neo4j/graphql v7 generates, use
compat.v7; both can be served side by side.
Create the schema
npm i @cyphra/graphql graphqlimport { native } from "@cyphra/graphql";
import { createClient } from "./cyphra.gen";
import { api } from "./graphql.config";
const db = createClient({ uri, user, password });
export const schema = native.makeSchema({ client: db, config: api });makeSchema returns a GraphQLSchema with its resolvers: serve it with GraphQL Yoga, Apollo
Server or any GraphQL server.
| Option | Description |
|---|---|
client | The client of cyphra.gen.ts (possibly $extends-ed), or a function of the GraphQL context returning the request’s client: (ctx) => db.$extends(…). |
schema | The schema model. Default: client.$schema. Required when client is a function. |
config | The API’s configuration, from defineGraphQL (below). Default: every read operation of every model, no writes. |
debug | Show the message of unexpected errors instead of Internal server error. |
With a function as client, every root field runs through that request’s client, so the client’s
query hooks run (multi-tenancy, soft delete, audit logs). Hooks wrap the root
operation only, as in the client.
Configure it
import { defineGraphQL } from "@cyphra/graphql/native";
import type { CyphraTypeMap } from "./cyphra.gen";
export const api = defineGraphQL<CyphraTypeMap>({
models: {
User: {
fields: {
passwordHash: false, // gone from every type and input
email: { filter: false, sort: false }, // readable, not usable in where / orderBy
},
},
AuditLog: { operations: { read: ["findMany", "count"] } },
Session: { operations: { read: false } },
Post: { operations: { create: true, update: true, delete: ["delete"] } },
},
naming: { Person: { findMany: "people" } },
limits: { maxDepth: 4, maxTake: 100, maxAliases: 20, maxComplexity: 10_000 },
});Every key is typed from CyphraTypeMap: { pasword: false } or a model that does not exist is a
compile error. makeSchema checks the config again at startup (for JavaScript, or configs built
dynamically) and throws a NativeSchemaError naming the unknown model, field or option. It
also refuses a model whose create is on while a required field without a default cannot be set
(fields: { passwordHash: false } with create: true), create on an interface and writes on a
union.
| Key | Description |
|---|---|
models.<M>.operations | Per group, true, false or a list of operations: read (findUnique, findFirst, findMany, count), create (create, createMany, upsert), update (update, updateMany, upsert), delete (delete, deleteMany). upsert is served when both create and update include it. Turning an operation off removes its root field. |
models.<M>.fields.<f> | false hides the field everywhere, writes included. { read, filter, sort, create, update } toggle reading it, filtering and sorting on it, and setting it in create / update inputs (for a relation: its nested writes). { read: false, create: true } is a write-only field. read may also be a field rule. { deprecated: "reason" } emits @deprecated. A toggle on an interface applies to its implementations. |
models.<M>.rules | Row-level rules, compiled into every statement that reaches the model. |
models.<M>.authenticated | Operations that need an authenticated request (authenticated). |
isAuthenticated | (ctx) => boolean: whether a request is authenticated. Default: the context has a user or a jwt. |
defaults.operations | The default of every model, per group. Reads are on, writes off. |
naming.<M>.<operation> | A root field name replacing <model><Operation> (reads and writes). It is part of the printed contract. |
relay | true adds Relay’s Node interface and node(id) (Relay). Off by default. |
limits | Checked before the statement is built (see Limits). |
mutationTransaction | "field" (default): each mutation root field is its own transaction. "request": every root field of a mutation operation in one transaction (see Transactions). |
generator | The generator version the printed SDL follows. Only 1 today. |
Naming
Root fields are <model><Operation>: no pluralization, and the fields of a model sort together.
node BlogPost gives blogPostFindMany and blogPostCreate. Types keep the model names; inputs
are <Model>Where, <Model>WhereUnique, <Model>OrderBy, <Model>CreateInput,
<Model>UpdateInput; filters are shared per scalar type (StringFilter, IntFilter,
DateTimeFilter, …).
GraphQL names cannot contain $, so the client’s $ keys become _ keys:
| Client | GraphQL |
|---|---|
db.post.findMany(args) | postFindMany(...) |
select / include | the selection set |
$edge | _edge |
$labels | _labels |
$on in where | _on |
$on in select | inline fragments: ... on Employee { salary } |
__typename in where / orderBy | _typename |
where: { email: "a@x.io" } (bare value) | where: { email: { equals: "a@x.io" } } |
orderBy: { createdAt: "desc" } | orderBy: [{ createdAt: desc }] |
data: { views: { increment: 1 } } | data: { _ops: { views: { increment: 1 } } } |
A model field named like one of these (_edge, _count, _labels, _on, _typename, _score,
_scores, _ops) is a makeSchema error: rename it in schema.cyphra.
Queries
type Query {
userFindUnique(where: UserWhereUnique!): User
userFindFirst(where: UserWhere, orderBy: [UserOrderBy!], skip: Int): User
userFindMany(
where: UserWhere
orderBy: [UserOrderBy!]
skip: Int
take: Int
after: String
before: String
): UserList
userCount(where: UserWhere): Int
}
type UserList {
nodes: [User!]!
pageInfo: PageInfo!
totalCount: Int!
}userFindUniquetakes the model’s@id/@uniquefields as bare values (and@@uniquekeys as objects), plus filters on the other fields. At least one key is required: awherewithout one is aBAD_USER_INPUTerror.- Root fields are nullable: a failing root field is
nullwith its error, and the other root fields of the query still return.
Lists and paging
There is one list query per model, for offset and cursor paging:
query Feed($after: String) {
postFindMany(
where: { published: { equals: true } }
orderBy: [{ createdAt: desc }]
take: 20
after: $after
) {
nodes {
id
title
author {
name
}
}
pageInfo {
hasNextPage
endCursor
}
totalCount
}
}skip/takepage by offset;after/beforepage by cursor, after or before apageInfo.endCursor/startCursor.afterwithskipskips within the page after the cursor.- Cursors are keyset cursors (the client’s
cursor): theorderByvalues of the boundary node and its@id. A page after a cursor does not shift when nodes are inserted before it. A cursor made for anotherorderByor another model, or a malformed one, is aBAD_USER_INPUTerror, never the first page. pageInfoloads one row more thantaketo tell whether there is a next page (a previous one withbefore). Paging forward,hasPreviousPageistruewhenafterorskipis given.totalCount(the number of nodes matchingwhere) is only counted when selected, in the same read transaction as the page.
Filters
<Model>Where mirrors the client’s where:
query {
userFindMany(
where: {
OR: [{ role: { equals: ADMIN } }, { email: { endsWith: "@acme.io", mode: insensitive } }]
posts: { some: { published: { equals: true } } }
name: null
}
) {
nodes {
email
}
}
}- Operators are the client’s (table):
equals,not,in,notIn,lt,lte,gt,gte,contains,startsWith,endsWith,mode: insensitive; list fields takehas,hasEvery,hasSome,isEmpty,equals; points takedistanceandwithinBBox. name: nulland{ equals: null }match nodes without the property;{ not: null }the others.- To-many relations take
some,none,every;some: {}means “has at least one”. To-one relations takeis,isNot;author: nullmeans “has none”. Vectorfields cannot be filtered or sorted on (use the client’sfindSimilar).
Ordering
orderBy is a list with one key per element (input object field order is not reliable in
every client library); two keys in one element are a BAD_USER_INPUT error.
orderBy: [
{ author: { name: asc } } # to-one: a field of the related node
{ tags: { _count: desc, where: { name: { startsWith: "a" } } } } # to-many: their number
{ createdAt: desc }
]Point fields sort by distance: { location: { distanceFrom: { longitude: 2.35, latitude: 48.85 } } }.
Relations, _edge and _count
To-many relations take where, orderBy, skip and take, as a nested include of the client;
to-one relations are nullable objects. The same relation can be loaded twice under aliases, still
in one statement:
query {
userFindUnique(where: { email: "alice@acme.io" }) {
recent: posts(orderBy: [{ createdAt: desc }], take: 3) {
title
}
popular: posts(orderBy: [{ views: desc }], take: 3) {
title
}
following(orderBy: [{ name: asc }]) {
name
_edge {
since
}
}
_count {
posts
followers(where: { role: { equals: ADMIN } })
}
}
}- Edge properties of a relation with a
relationship { … }model are the_edgefield of the node it leads to: no connection types. Selecting_edgeon a node that was not reached through such a relation (a root, or another relation) is aBAD_USER_INPUTerror, not a silentnull. When several relationship models lead to a node,_edgeis a union of them (union UserEdge = Blocks | Follows), selected with inline fragments. _countcounts the related nodes of each selected to-many relation (only those), optionally filtered. A relation can be counted once per selection.
Interfaces and unions
Cyphra interfaces (a label shared by their implementations) are GraphQL interfaces; unions are
GraphQL unions. Inline fragments and fragment spreads are the client’s $on: each implementation’s
selection is evaluated only on its nodes, in the same statement.
query {
personFindMany(
where: { _on: { Employee: { salary: { gt: 100 } }, Customer: {} } }
orderBy: [{ _typename: asc }, { name: asc }]
) {
nodes {
__typename
name
manager {
name
}
... on Employee {
salary
}
}
}
customers: personCount(where: { _typename: { in: [Customer] } })
}_typenamefilters and sorts by implementation (an enum of them);_onkeeps the listed implementations matching their ownwhere.- A union has
findFirst,findManyandcount(no unique key, so nofindUnique). - An interface without fields (
interface Archivable {}) is served as a union of its implementations: GraphQL interfaces need at least one field.
Mutations
Writes are off by default: a model is writable through the API once its config turns them on
(operations: { create: true, update: true, delete: true }, or a list per group). Each operation
is one root field of Mutation, run as one client operation:
type Mutation {
postCreate(data: PostCreateInput!): Post
postCreateMany(data: [PostCreateManyInput!]!): PostBatch
postUpdate(where: PostWhereUnique!, data: PostUpdateInput!): Post
postUpdateMany(where: PostWhere, data: PostUpdateManyInput!): PostBatch
postUpsert(where: PostWhereUnique!, create: PostCreateInput!, update: PostUpdateInput!): Post
postDelete(where: PostWhereUnique!): Post
postDeleteMany(where: PostWhere): PostBatch
}
type PostBatch {
count: Int!
nodes: [Post!]!
}- Mutations return records: the created, updated or upserted node, the deleted node as it was.
Batch mutations return
countand, when selected, the affectednodes(the deleted ones as they were), read in the same statement with the client’s batchselect. createManyandupdateManytake scalars only (<Model>CreateManyInput,<Model>UpdateManyInput), as in the client: nested writes go throughcreate/update.- Mutation root fields are nullable, like queries: a failing one is
nullwith its error.
Nested writes
Relations in <Model>CreateInput take create and connect; in <Model>UpdateInput also
disconnect (a list on to-many, disconnect: true on to-one) and, on to-many, set:
mutation {
userUpdate(
where: { id: "u1" }
data: {
name: "Alice"
_ops: { loginCount: { increment: 1 } }
following: {
connect: [{ email: "bob@acme.io", _edge: { since: "2026-11-01T00:00:00Z" } }]
disconnect: [{ email: "carol@acme.io" }]
}
posts: { create: [{ title: "Hello", tags: { connect: [{ name: "graphs" }] } }] }
}
) {
name
following {
email
_edge {
since
}
}
}
}connectis aMERGE: connecting a pair that is already linked keeps one edge and updates the_edgeproperties given (edge defaults are set only when the edge is created). On a to-one relation,connect(orcreate) replaces the edge; when the other side is to-one (connecting a post throughuser.postswhilePost.authorisUser?), the post moves. Numeric_edgeproperties take_opsonconnect/set:_edge: { _ops: { weight: { increment: 1 } } }.setmakes the listed nodes the only linked ones (edges to the others are deleted, the listed ones are kept or connected).- Inputs are generated per relation side: a nested create omits the back relation
(
UserCreateWithoutPostsInputhas noposts), and its relation input is named after it (PostCreateManyWithoutAuthorRelation). Items of a typed edge take_edge;connectitems are the target’s unique key plus_edge(UserConnectFollows). - A model whose
createis off has no nested create either: withTagread-only,PostCreateInput.tagshasconnectonly. Nestedupdate,delete,upsertandconnectOrCreateare not served yet. - Unions take a member-keyed item (
{ Post: { … } }); an interface is connected by its unique key, and created through its implementations.
Scalar updates
A field of <Model>UpdateInput takes the new value; null removes the property (a required field
cannot be null: BAD_USER_INPUT). Numeric operators go in _ops, applied in order:
_ops: { views: { increment: 1 }, score: { multiply: 2 } }. Setting a field and an _ops
operator on it is a BAD_USER_INPUT error. @min / @max are checked on the value an operator
produces.
Validation
Validation rules (@length, @min, @email, …) and enum values are checked before anything is
written, as in the client. The error lists every broken rule in extensions.issues, with paths in
GraphQL argument terms:
{
"message": "User.create: 1 value breaks the schema's validation rules: …",
"extensions": {
"code": "BAD_USER_INPUT",
"issues": [
{
"path": ["data", "posts", "create", 1, "title"],
"model": "Post",
"field": "title",
"rule": "length",
"message": "must be at least 3 characters long (got 2)."
}
]
}
}A rule broken by an _ops update has _ops in its path (["data", "_ops", "loginCount"]).
Transactions
Each mutation root field is its own transaction (by default), and the fields of one operation run
in order. With mutationTransaction: "request", every root field of a mutation operation runs in
one write transaction (one statement each, in order): they commit together or not at all.
The first failing field rolls the whole operation back, the remaining fields are not run, and
every root field is null with that field’s error (nothing it reported was committed).
Auth
Authorization is configured in graphql.config.ts, next to the operations it guards, as
TypeScript functions of the request’s context. Rules are schema-level and compiled into the
statement: the same where the client compiles is ANDed into every place the model is matched,
so nothing is filtered in JavaScript and no query can read around a rule.
import { defineGraphQL } from "@cyphra/graphql/native";
import type { CyphraTypeMap } from "./cyphra.gen";
type Ctx = { user?: { id: string; role: "MEMBER" | "ADMIN" } };
const me = (ctx: Ctx) => ctx.user?.id ?? "";
export const api = defineGraphQL<CyphraTypeMap, Ctx>({
models: {
User: {
operations: { update: ["update"] },
fields: {
passwordHash: false,
email: { read: { where: ({ ctx }) => ({ id: me(ctx) }) } }, // each user reads their own
salary: { read: ({ ctx }) => ctx.user?.role === "ADMIN" }, // admins only
},
rules: { update: ({ ctx }) => ({ id: me(ctx) }) },
},
Post: {
operations: { create: true, update: true, delete: true },
authenticated: { create: true, update: true, delete: true },
rules: {
read: ({ ctx }) => ({ OR: [{ published: true }, { author: { is: { id: me(ctx) } } }] }),
update: ({ ctx }) => ({ author: { is: { id: me(ctx) } } }),
delete: ({ ctx }) =>
ctx.user?.role === "ADMIN" ? true : { author: { is: { id: me(ctx) } } },
after: { create: ({ ctx }) => ({ author: { is: { id: me(ctx) } } }) },
connect: { tags: () => ({ internal: false }) },
},
},
AuditLog: { rules: { read: () => false } },
},
});Authentication
makeSchema does not verify tokens: the server’s context function does, and Ctx types what
rules see. native.jwtContext builds such a context from the Authorization: Bearer <jwt> header,
with the same verifier as compat.v7’s features.authorization, so both APIs can share one
context function:
import { createYoga } from "graphql-yoga";
import { native } from "@cyphra/graphql";
const yoga = createYoga({
schema,
context: native.context(
schema,
native.jwtContext({
key: process.env.JWT_SECRET!, // or { url: "https://…/.well-known/jwks.json" }
verifyOptions: { issuer: "https://auth.example.com", audience: "api" },
user: (jwt) => ({ id: jwt.sub!, role: jwt.role as "MEMBER" | "ADMIN" }),
}),
),
});- The context is
{ token, jwt, user }:jwtis the verified payload,userwhat theuseroption makes of it. A missing, malformed, expired or forged token leaves the request anonymous (nojwt, nouser), as incompat.v7. It reads{ request }(GraphQL Yoga, Fetch servers) or{ req }(Apollo Server on Node). - Any context function works:
context: async ({ request }) => ({ user: await verify(request) }). native.context(schema, build)(optional) also setsctx.cyphrabefore any resolver runs.
authenticated
models.<M>.authenticated names the operations that need an authenticated request: true (all of
them) or per group, like operations ({ create: true, update: ["update"] }). An anonymous request
gets UNAUTHENTICATED before anything runs. A request is authenticated when
config.isAuthenticated(ctx) says so (default: the context has a user or a jwt).
A whole group (read: true, create: true, …) also applies wherever the model is reached: for an
anonymous request, the model’s nodes are not there in relations, _count and relation filters
(read), and nested writes cannot create or update them. A list of operations guards only those
root fields.
Rules
A rule is a function of { ctx } returning true (allowed), false (denied) or a where on the
model, typed as the client’s where of that model:
| Rule | Applies to |
|---|---|
read | Every read of the model: root fields, relation loads at any depth, relation filters (some / none / every / is), _count, totalCount, mutation results, and the targets of writes. |
create | ({ ctx, data }) => boolean: each node created, root or nested, from its create data, before anything runs. |
update | The nodes update / updateMany / upsert match, whatever they write (scalars, relations only, or nothing). |
delete | The nodes delete / deleteMany match. |
connect.<relation> | The targets a nested connect / set may link (a where on the target model). |
disconnect.<relation> | The targets a nested disconnect / set may unlink. |
after.create / .update | Checked on the nodes created / updated once every write of the statement ran (nested ones included); a node that does not match rolls the whole write back. |
- Compiled, not filtered in JavaScript. A
whererule is the client’swhere: relations,_on,_labels, anything a filter can do. Context values are parameters. A rule’s ownwhereis not subject to other rules. - Evaluated once per request, against its context, and shared by its root fields.
- Denied vs not found. An
update/delete/connecton a node outside its rules fails withNOT_FOUND: the node does not exist for this request, so a rule never reveals that a key exists. A node the request cannotreadcannot be updated, deleted, connected or disconnected either.false(the whole operation denied) fails the root field withFORBIDDEN; a failingcreateorafterrule isFORBIDDENtoo, and nothing is written. - Relationships. Connecting a node whose other side is to-one (
user.posts.connectmoves a post from its author) is an update of that node: itsupdaterule applies. A to-one edge a write must replace (connectorcreateonpost.author) is a disconnect of the current target: outside thedisconnectrule, the write isFORBIDDEN. Explicitdisconnect/setleave the edges outside the rule alone. - Mutation results apply
read: relations of the written node show what the request can read, field rules apply, and a written node the request cannot read is returned asnull(the write happened). Batchnodesleave such nodes out. - Interfaces and unions. A rule on an interface applies to every implementation; a node matched through an interface or a union gets its own model’s rules too.
- Startup check. Rule keys, models and relations are typed from
CyphraTypeMap, andmakeSchemachecks them again. It also calls everywhererule once with an empty context ({ ctx: {} }) and checks the fields and relations of thewhereit returns, so{ publishd: true }fails at startup even in JavaScript. A rule that throws without a context is checked on its first request (an invalidwherethen fails that request withINTERNAL_SERVER_ERROR).
TypeScript checks object literals returned by a function only partly: ({ publishd: true }) and
({ author: { is: { emial: "x" } } }) fail tsc, but a misspelled key next to a correct one
(({ published: true, publishd: true })) does not. The startup check catches it.
On FalkorDB, which cannot roll a write back, after rules and disconnect rules are refused.
Field rules
fields.<f>.read takes a rule instead of a boolean. A field with a rule is generated nullable.
- Context-only:
read: ({ ctx }) => boolean, evaluated once per request. A denied field selected isnullwith aFORBIDDENerror at its path (extensions.fieldnames it); using it inwhere,orderBy(also through a relation) or_countfails the root field withFORBIDDENbefore anything runs. - Row-dependent:
read: { where: ({ ctx }) => … }, compiled toCASE WHEN <where> THEN n.email END. The field isnullon the rows thewheredoes not match, and filters, ordering, unique lookups and mutation results see thatnulltoo: no query can probe the hidden values. Scalar fields only; not the@idfield.
A rule on a field of an interface goes on the interface and applies to every implementation.
ctx.cyphra
ctx.cyphra is the request’s client with the API’s rules applied (the same rules as the
generated root fields), for custom resolvers and anything else that reads on the request’s
behalf; ctx.cyphra.$unsafe is the client without them, for the rare code that must.
const yoga = createYoga({ schema, context: native.context(schema, native.jwtContext({ key })) });
// In a resolver:
const drafts = await ctx.cyphra.post.findMany({ where: { published: false } }); // only readable ones
const all = await ctx.cyphra.$unsafe.post.count(); // no rulesnative.context(schema, build) sets it before any resolver runs. Without it, the first generated
root field of the request sets it, when the context has no cyphra of its own.
Hooks
Rules are declarative and reach every place a model appears in a statement. Query
hooks (a client function: (ctx) => db.$extends(…)) are code around one
root operation: they do not run for post loaded under user { posts }. Use a rule for
anything that must hold wherever a model is reached, and hooks for the rest (hashing a password,
audit logs, soft delete).
Security guide
Checklist for an API exposed to untrusted clients:
- Expose on purpose. Writes are off by default; turn on the operations each model needs, per
group or per operation. Hide fields no client should see with
fields: { f: false }. - Guard data with rules, not with toggles.
operations: { read: false }removes root fields only: the model is still reached through relations.rules: { read }hides its nodes everywhere. - Write
update/deleterules for every writable model, andafter.create(or acreaterule) to constrain what a create may produce, such as the author being the requester. - Guard relationships.
connect/disconnectrules restrict what nested writes may link; remember that connecting through a to-many side can move a node off its to-one owner (itsupdaterule applies). - Use field rules for sensitive values (emails, salaries): they cannot be filtered, sorted or looked up by unique key around the rule.
- Use
ctx.cyphrain custom resolvers, so they apply the same rules; keep$unsafefor code that must bypass them, and review it. - Set limits (
maxDepth,maxTake,maxComplexity) to bound what one request may load, and leavedebugoff in production. - Commit the printed contract (
cyphra graphql print --check) so a change in what the API exposes shows up in review.
What the native API fixes over @neo4j/graphql v7 (each has a test in
packages/graphql/test/native.auth.integration.test.ts and the auth fixture of the compat
suite):
| v7 | Native API |
|---|---|
@mutation(operations: []) hides root mutations; a nested create through another type works | A model whose writes are off has no nested create; a create rule holds through nested writes. |
@query(read: false) types are readable through relationships | A read rule hides the nodes in relations, _count, relation filters and connects. |
where / sort / aggregation filters can probe fields and nodes the user cannot read | Filters and sorting only see readable nodes, and ruled fields as null (or FORBIDDEN). |
AGGREGATE rules are separate from READ rules | One read rule covers counts, totalCount and _count. |
Relationship-only updates skip the node’s UPDATE rules | update restricts every update, whatever it writes; connects that move a node need its update. |
create responses ignore READ rules | Mutation results apply read and field rules. |
| Rules are strings in SDL directives, checked when the schema is built | Rules are TypeScript, typed against schema.cyphra, and checked again at startup. |
Scalars
| Cyphra | GraphQL |
|---|---|
String with @id | ID |
String, Int, Float, Boolean | the same (Int is GraphQL’s 32-bit Int: use BigInt above it) |
DateTime | DateTime (ISO 8601: 2026-11-01T09:30:00.000Z) |
Date | Date (yyyy-mm-dd) |
LocalDateTime, LocalTime, Time, Duration | the same names, ISO 8601 strings |
BigInt | BigInt (a decimal string) |
Json | Json (any JSON value) |
Point, CartesianPoint | objects ({ longitude latitude height }, { x y z }), PointInput |
Vector(N) | [Float!] |
enum | a GraphQL enum |
@@labels([…]) | _labels: [String!]!, filtered with _labels: { has, hasSome, … } |
Optional fields are nullable; required ones are non-null; lists are [T!]!.
Limits
config.limits bounds what one root field may ask the database to load. Each is checked before
the statement is built; exceeding one fails the root field with BAD_USER_INPUT and
extensions.limit naming it.
| Limit | Description |
|---|---|
maxDepth | Deepest relation nesting (a root’s relations are depth 1). |
maxTake | Largest take of a list, root or relation; also the take of a list that sets none. |
maxAliases | Most aliased fields in one root field’s selection. |
maxComplexity | Most rows a root field may load: each list multiplies its parent’s rows by its take (maxTake, or 100, when it has none). |
Errors
Errors carry a stable extensions.code, mapped from the client’s errors:
| Error | extensions.code | extensions |
|---|---|---|
CyphraValidationError (bad input, invalid cursor, no unique key) | BAD_USER_INPUT | issues (paths in GraphQL argument terms) when the client lists some |
_edge outside its context, two keys in one orderBy element | BAD_USER_INPUT | |
a value and an _ops operator on one field, null for a required field | BAD_USER_INPUT | |
| a limit exceeded | BAD_USER_INPUT | limit |
NotFoundError (update / delete / connect target missing) | NOT_FOUND | |
RestrictError | RESTRICTED | model, relation, target, count |
UniqueConstraintError (a duplicate @id / @unique value) | UNIQUE_CONSTRAINT | model, fields, constraint (never the value) |
authenticated and an anonymous request | UNAUTHENTICATED | model, operation |
a rule denying the whole operation (false) | FORBIDDEN | model, operation |
a create rule, an after rule, a to-one replace outside disconnect | FORBIDDEN | model, operation (relation) |
| a field a context-only rule denies (selected, filtered, sorted) | FORBIDDEN | model, field |
| anything else (driver, bug) | INTERNAL_SERVER_ERROR | message masked unless debug: true |
Relay
relay: true in the config adds Relay’s Node interface and a node(id: ID!) root field:
interface Node {
id: ID!
}
type Post implements Node {
id: ID! # the global id
rawId: ID! # the post's own id field
title: String!
}
type Query {
node(id: ID!): Node
}- Every model with an
@idfield of typeString,IntorBigIntimplementsNode(an interface with one implements it too). Its global id isbase64("<Type>:<id>");native.toGlobalId/native.fromGlobalIdbuild and read them on the server. - The model’s own field named
idis returned asrawId, sinceidis the global id. Inputs (where,orderBy,<model>FindUnique) keepidwith raw values. A model with a field already namedrawIdis amakeSchemaerror. node(id)is onefindUnique. It returnsnullfor an id of an unknown type, of a model whose reads are all off, or of a node that does not exist; a string that is not a global id is aBAD_USER_INPUTerror.
Relay is off by default.
Print and check the contract
The generated SDL is deterministic: printed with lexicographicSortSchema and printSchema,
descriptions included. Commit it and check it in CI, so a field removed by a schema edit or a
config toggle shows up in review:
cyphra graphql print --out schema.graphql # write it (reads graphql.config.ts)
cyphra graphql print --check # fails when schema.graphql is out of date--check lists the breaking and dangerous changes between the committed SDL and the generated one
(CLI reference). From code, native.printSchema(schemaModel, config) returns the same text. config.generator pins the generator version: a release that
would print something else for the same schema and config ships it as a new, opt-in version.
One statement per root field
A root field’s arguments and its whole selection (fragments resolved, @skip / @include
applied, variables substituted) are translated into one client operation, which compiles one
Cypher statement (COLLECT {} / COUNT {} subqueries for relations, CASE WHEN n:Label for
fragments). Nested fields do no I/O: a query runs as many statements as it has root fields,
whatever its depth. A findMany that selects totalCount with its nodes runs the page and the
count in one read transaction. A mutation root field (nested writes and the returned record
included) is one write statement too.
Side by side with compat.v7
The two APIs have types with the same names and different shapes, so they are served on separate endpoints, from the same client or driver and the same graph:
const v7 = compat.v7.makeSchema({ typeDefs, client: db.$client });
const v2 = native.makeSchema({ client: db, config: api });
// /api/graphql stays the v7 API; /api/graphql/v2 is the native one.Frontends move operation by operation: movies(where, sort, limit) becomes
movieFindMany(where, orderBy, take) { nodes }, actorsConnection { edges { properties } }
becomes actors { _edge { … } }, { eq: … } becomes { equals: … }. Keyset cursors are not
interchangeable with v7’s offset cursors. The migration guide
covers moving the type definitions to schema.cyphra (cyphra import graphql).