Relay
On this page
Relay is the strictest GraphQL client there is: it wants every record refetchable by a global id, every long list a connection, and every operation compiled ahead of time. A Gratos schema gives it all three, written by hand in TypeScript, with Effect resolvers. This site is the proof: it is a React Router app on Relay, and every page you read came from a Gratos server, through the code these pages quote.
The guide has four parts. This page is the schema: a Node interface and connections. @defer and @stream with Relay is the fetch function that turns gratos-server's incremental responses into what Relay reads. Server rendering preloads a route's query in process and hydrates with no request. Persisted queries makes the server run only the operations relay-compiler produced.
A Node interface
Relay refetches any record with node(id:), so every type it caches implements Node, whose id is global: unique across types, and the same for every query that reaches the record. In Gratos, Node is an interface marked @gqlInterface, a type implements it with implements, and node is a query field that decodes the id. Declared in a module, the interface can be named Node: it shadows the DOM's global Node instead of merging with it. The Global Object Identification spec wants id: ID!, and Gratos makes every field nullable by default, so id is marked @killsParentOnException, on the interface and on every type that implements it: it is non-null, and an error in it nulls the record that holds it:
import type { ID } from "gratos";
import { Effect, Schema } from "effect";
/**
* An object with a global id.
* @gqlInterface
*/
export interface Node {
/**
* @gqlField
* @killsParentOnException
*/
readonly id: ID;
}
/** @gqlType */
export class Author implements Node {
__typename = "Author" as const;
/**
* @gqlField
* @killsParentOnException
*/
readonly id: ID;
/** @gqlField */
readonly name: string;
constructor(key: string, name: string) {
this.id = toGlobalId("Author", key);
this.name = name;
}
}
/** A global id: the type's name and the record's own key, base64url-encoded. */
export const toGlobalId = (type: string, key: string): ID =>
Buffer.from(`${type}:${key}`, "utf8").toString("base64url");
export class InvalidId extends Schema.TaggedError<InvalidId>()("InvalidId", {
id: Schema.String,
}) {}
const AUTHORS = new Map([["ada", "Ada Lovelace"]]);
/** Any record, by its global id. @gqlQueryField */
export function node(id: ID): Effect.Effect<Node, InvalidId> {
return Effect.gen(function* () {
const [type, key] = Buffer.from(id, "base64url").toString("utf8").split(":");
const name = key === undefined ? undefined : AUTHORS.get(key);
if (type !== "Author" || key === undefined || name === undefined) {
return yield* new InvalidId({ id });
}
return new Author(key, name);
});
}"""An object with a global id."""
interface Node {
id: ID!
}
type Author implements Node {
id: ID!
name: String
}
type Query {
"""Any record, by its global id."""
node(id: ID!): Node
}A type that implements an interface declares its __typename as a constant, so the executor can tell which type a Node is. The id here is the type's name and the record's own key, base64url-encoded; this site encodes its ids the same way, and decodes them back:
export const fromGlobalId = (id: string): { type: string; key: string } | undefined => {
const decoded = Buffer.from(id, "base64url").toString("utf8");
const colon = decoded.indexOf(":");
if (colon <= 0 || toGlobalId(decoded.slice(0, colon), decoded.slice(colon + 1)) !== id) {
return undefined;
}
return { type: decoded.slice(0, colon), key: decoded.slice(colon + 1) };
};Its node resolver is an Effect over the content index: it reads the Content service, looks the record up by its type and key, and fails with its typed InvalidId when there is none, which the server answers as a NOT_FOUND error:
/** Any record, by its global id. @gqlQueryField */
export function node(id: ID): Effect.Effect<Node, AppError, Content> {
return Effect.gen(function* () {
const parsed = fromGlobalId(id);
const found = parsed === undefined ? undefined : yield* lookup(parsed.type, parsed.key);
if (found === undefined) {
return yield* new InvalidId({ id });
}
return found;
});
}Every record type of this site's content index is a Node: Page, Heading, NavSection, CodeSample and ChangelogEntry, each with an id: ID!. The connections and their page info are not records, and have no id. Its tests refetch every record of the index through node(id:) and check that each one comes back as the record its own path reaches.
Connections
A long list is a connection, in the shape of Relay's connection spec: edges, each with a node and a cursor, and the page info. Grats' generics fit it: Connection<T> is a generic type, and Gratos writes one BookConnection (and one BookEdge) for each T it is used with. The spec wants pageInfo: PageInfo!, with both cursors and the hasNextPage: Boolean! and hasPreviousPage: Boolean! flags, so those three fields are marked @killsParentOnException. The resolver is an Effect like any other:
import type { Int } from "gratos";
import { Effect } from "effect";
/** @gqlType */
export type Connection<T> = {
/** @gqlField */
readonly edges: ReadonlyArray<Edge<T>>;
/**
* @gqlField
* @killsParentOnException
*/
readonly pageInfo: PageInfo;
};
/** @gqlType */
export type Edge<T> = {
/** @gqlField */
readonly node: T;
/** @gqlField */
readonly cursor: string;
};
/** @gqlType */
export type PageInfo = {
/** @gqlField */
readonly startCursor: string | null;
/** @gqlField */
readonly endCursor: string | null;
/**
* @gqlField
* @killsParentOnException
*/
readonly hasNextPage: boolean;
/**
* @gqlField
* @killsParentOnException
*/
readonly hasPreviousPage: boolean;
};
/** @gqlType */
export type Book = {
/** @gqlField */
readonly title: string;
};
const BOOKS: ReadonlyArray<Book> = [{ title: "Dune" }, { title: "Emma" }, { title: "Ulysses" }];
/** Every book, `first` at a time. @gqlQueryField */
export function books(first: Int, after?: string | null): Effect.Effect<Connection<Book>> {
if (first < 0) {
// The connection spec makes a negative `first` an error.
return Effect.die(new RangeError("`first` must not be negative."));
}
return Effect.sync(() => {
const start = after === null || after === undefined ? 0 : Number(after) + 1;
const edges = BOOKS.slice(start, start + first).map((node, index) => ({
node,
cursor: String(start + index),
}));
return {
edges,
pageInfo: {
startCursor: edges[0]?.cursor ?? null,
endCursor: edges.at(-1)?.cursor ?? null,
hasNextPage: start + first < BOOKS.length,
hasPreviousPage: start > 1,
},
};
});
}type Book {
title: String
}
type BookConnection {
edges: [BookEdge!]
pageInfo: PageInfo!
}
type BookEdge {
cursor: String
node: Book
}
type PageInfo {
endCursor: String
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
}
type Query {
"""Every book, `first` at a time."""
books(after: String, first: Int!): BookConnection
}This site's lists page through one function: the items after the after cursor, first of them and never more than 50, as edges with cursors and the page info. It is an Effect, so a cursor that is not one of the list's fails with the app's typed error:
export const connectionOf = <A, T>(
items: ReadonlyArray<A>,
toNode: (item: A) => T,
args: { readonly first?: Int | null | undefined; readonly after?: string | null | undefined },
): Effect.Effect<Connection<T>, InvalidPage> =>
Effect.gen(function* () {
const { first, after } = args;
if (first !== null && first !== undefined && first < 0) {
return yield* new InvalidPage({ reason: "`first` must not be negative." });
}
let start = 0;
if (after !== null && after !== undefined) {
const offset = offsetOf(after);
if (offset === undefined || offset >= items.length) {
return yield* new InvalidPage({ reason: `${echoed(after)} is not a cursor of this list.` });
}
start = offset + 1;
}
const count =
first === null || first === undefined ? MAX_PAGE_SIZE : Math.min(first, MAX_PAGE_SIZE);
const end = start + count;
const edges = items
.slice(start, end)
.map((item, index) => ({ node: toNode(item), cursor: cursorOf(start + index) }));
return {
edges,
pageInfo: {
startCursor: edges[0]?.cursor ?? null,
endCursor: edges.at(-1)?.cursor ?? null,
hasNextPage: end < items.length,
hasPreviousPage: start > 1,
},
};
});A connection field is then a few lines. The changelog, newest first:
/** Every release of both packages, newest first. @gqlQueryField */
export function changelog(
first?: Int | null,
after?: string | null,
): Effect.Effect<Connection<ChangelogEntry>, AppError, Content> {
return Effect.gen(function* () {
const content = yield* Content;
const entries = yield* content.changelog();
return yield* connectionOf(entries, (row) => new ChangelogEntry(row), { first, after });
});
}On the client, @connection (or @stream_connection, which streams the edges) and usePaginationFragment page through it. The changelog's "Show more" is this fragment, which relay-compiler makes refetchable on Query:
fragment changelogEntries_query on Query
@refetchable(queryName: "changelogEntriesPaginationQuery")
@argumentDefinitions(first: { type: "Int!" }, after: { type: "String" }) {
changelog(first: $first, after: $after)
@stream_connection(key: "changelogEntries_changelog", initial_count: 1) {
edges {
node {
id
package
version
html
}
}
}
}The schema relay-compiler reads
relay-compiler reads the schema the gratos CLI writes, semantic nullability included. Two directives are missing from it: @defer and @stream, which gratos-server's incremental() plugin adds to the schema at startup. They must be part of relay-compiler's server schema: directives declared through its schemaExtensions are client-only to Relay, and it strips them from the query text it sends, so the server would never defer anything. This site appends them in a small script, which a check fails on when it is stale:
directive @defer(if: Boolean! = true, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT
directive @stream(if: Boolean! = true, label: String, initialCount: Int! = 0) on FIELDThe relay-compiler config points at that schema, writes TypeScript artifacts with import type, and persists every operation:
{
"src": "./app",
"schema": "./src/generated/relay-schema.graphql",
"artifactDirectory": "./src/generated/relay",
"language": "typescript",
"eagerEsModules": true,
"excludes": ["**/node_modules/**", "**/generated/**"],
"useImportTypeSyntax": true,
"persistConfig": {
"file": "./src/generated/persisted-documents.json",
"algorithm": "SHA256"
}
}