Server
The server core
On this page
gratos-server is a small GraphQL-over-HTTP server. createServer(options) returns a server, and its handle(request) takes a Web Request and returns a Promise<Response>, so the server runs behind any fetch-style adapter: Effect's HTTP platform (see The Effect layer), Node's http through a converter, or a test that calls it directly. The core never imports effect.
createServer
This site's server: the generated schema wrapped by effectSchema, and the plugins in their documented order.
return createServer({
schema: effectSchema(schema, { failure, isFailure: isAppError }),
plugins: [
incremental(),
trustedDocuments({ documents: options.documents }),
// `context`: resolvers find the app's services also when the server is used without a
// route (makeServer(...).handle(request) in a test); a route forks with its own context.
effect({ context: services }),
reportErrors((error) => {
report(error);
}),
maskErrors(),
],
});The options:
| Option | Default | What it does |
|---|---|---|
schema |
required | The executable schema. A Gratos schema with Effect resolvers is wrapped by effectSchema first |
rootValue |
none | The root value of every operation |
context |
none | (request, { operation, document, params }) => Ctx, once the operation is known. Required when Ctx excludes undefined |
plugins |
[] |
The plugins, in order (see Plugins) |
documentCacheSize |
1000 | The size of the validated-document cache, keyed by the schema's generation and the query's text |
maxTokens |
10000 | The most lexical tokens a document may have (graphql's maxLexicalTokens) |
maxBodyBytes |
1 MiB | The largest request body the core reads; a larger one gets a 413. A positive safe integer, or Infinity for no limit; anything else throws a RangeError |
sseHeartbeatMs |
30000 | A : comment line on an SSE stream that has sent nothing for this long, while the client reads. A positive integer, or false for none |
logger |
console |
{ warn, error }, for drain warnings and failing hooks |
createServer returns { handle, control }:
readonly handle: (request: Request) => Promise<Response>;
readonly control: ServerControl;control has schema(), generation(), replaceSchema(schema), drain({ warnAfterMs }), draining(), closeStreams() and closingStreams() (see GraphQL over HTTP). replaceSchema starts a new generation: requests in flight finish on the schema they started with. Per request, a plugin reads signalOf(request) (the core's abort signal), startOf(request) (when handle() received it) and mutationOf(request) (a mutation's started, settled and status).
One Request object, one handle() call. Every per-request state is keyed by the Request, so never pass it to handle() again while an earlier call on it is in flight, a streamed body included. Parallel calls need distinct Request objects.
Hooks, in call order
A plugin is an object of optional hooks. The hook lists are built once, at startup, so a hook no plugin defines costs nothing. The order below is for a query whose document is not cached yet: its parse and validate phases reach onPhase before onContext.
| Hook | When | Sync |
|---|---|---|
onServer |
Once, at startup. May replace the schema (control.replaceSchema) |
no |
onReady |
Once at startup, after every onServer hook has settled, and on every later replaceSchema: gets a schema and the validation rules, and throws to refuse it |
yes |
onRequest |
First, when handle() is called. Returning a Response answers the request |
no |
onParams |
After the body is read, before the "no query" check. Returns replacement params, or nothing. A throw is a 400 | no |
onPhase |
A finished phase: parse and validate on a cache miss, jit when it compiles | yes |
onContext |
After the context factory, once the operation is known, before anything executes | no |
onExecute |
Every hook, in list order, before anything executes. Returns an executor to claim the operation, or throws to refuse it | yes |
wrapExecution |
Around each synchronous entry into the execution: the executor call, each source pull, each event. Calls run once |
yes |
onResult |
Every payload: a result, each incremental payload, each subscription event. Returns a replacement, or nothing | yes |
onResponse |
Exactly once per request, on the Response before it goes to the transport, a streamed one too. Not a "stream ended" hook | no |
Two more members are read once, at startup: validationRules, run with graphql's own rules on every document the cache does not hold yet, and hideSuggestions (which maskErrors() sets).
onReady({ schema, validationRules }) checks a schema before the server serves it, with the rules the core will validate that schema's documents with. At startup, a refusal throws from createServer() when startup is synchronous, and fails the startup when an onServer hook is async: the error is logged once, and every request gets a 500. After startup, replaceSchema(next) runs every onReady on next first; when one throws, the current schema keeps serving, and replaceSchema rethrows.
Writing a plugin
A whole plugin, readOnly(), which refuses every mutation before it starts:
export const readOnly = (): Plugin => ({
name: "readOnly",
onExecute: ({ operation }) => {
if (operation.operation === "mutation") {
throw gqlError("This server is read-only.", 403, { code: "READ_ONLY" });
}
return undefined;
},
});The rules a plugin keeps:
Refusals do not depend on order. Every
onExecutehook runs before any executor is called, and a thrownGraphQLErrorrefuses the operation whatever earlier hooks returned. The first executor returned is the one called; itsnext()runs the next claim, or the default executor. A subscription always runs through graphql-js.The body rule. A plugin that replaces the Response in
onResponsekeepsresponse.body, reusing it or wrapping it in a pass-through stream, because body wrappers (the Effect layer's span end) depend on it.serverTiming()is the reference:packages/gratos-server/src/plugins/serverTiming.ts return new Response(response.body, { status: response.status, statusText: response.statusText, headers, });wrapExecutionand executors must not throw, afterrunor afternext(). A throw is handled on a best-effort basis only, and work started in that instant may not be stopped.
The answers the core gives, status by status, are in GraphQL over HTTP; the plugins that ship with it are in Plugins.