@softistx/alxia-graphql 0.0.0-stage → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -2
  3. package/dist/bounded-stream.d.ts +37 -0
  4. package/dist/bounded-stream.d.ts.map +1 -0
  5. package/dist/endpoint.d.ts +17 -0
  6. package/dist/endpoint.d.ts.map +1 -0
  7. package/dist/executor.d.ts +49 -0
  8. package/dist/executor.d.ts.map +1 -0
  9. package/dist/explorer.d.ts +24 -0
  10. package/dist/explorer.d.ts.map +1 -0
  11. package/dist/graphql.d.ts +63 -0
  12. package/dist/graphql.d.ts.map +1 -0
  13. package/dist/handler.d.ts +11 -0
  14. package/dist/handler.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +621 -0
  18. package/dist/index.js.map +21 -0
  19. package/dist/once-per-request.d.ts +28 -0
  20. package/dist/once-per-request.d.ts.map +1 -0
  21. package/dist/operation.d.ts +3 -0
  22. package/dist/operation.d.ts.map +1 -0
  23. package/dist/options.d.ts +38 -0
  24. package/dist/options.d.ts.map +1 -0
  25. package/dist/removed.d.ts +14 -0
  26. package/dist/removed.d.ts.map +1 -0
  27. package/dist/sandbox.d.ts +15 -0
  28. package/dist/sandbox.d.ts.map +1 -0
  29. package/dist/testing/client.d.ts +95 -0
  30. package/dist/testing/client.d.ts.map +1 -0
  31. package/dist/testing/index.d.ts +2 -0
  32. package/dist/testing/index.d.ts.map +1 -0
  33. package/dist/testing/index.js +73 -0
  34. package/dist/testing/index.js.map +10 -0
  35. package/dist/ws.d.ts +30 -0
  36. package/dist/ws.d.ts.map +1 -0
  37. package/docs/README.md +31 -0
  38. package/docs/guide/context.md +351 -0
  39. package/docs/guide/endpoint.md +293 -0
  40. package/docs/guide/executor.md +75 -0
  41. package/docs/guide/ide.md +160 -0
  42. package/docs/guide/plugins.md +316 -0
  43. package/docs/guide/production.md +374 -0
  44. package/docs/guide/testing.md +171 -0
  45. package/docs/guide/websockets.md +329 -0
  46. package/docs/migrating-to-graxia.md +408 -0
  47. package/docs/roadmap.md +122 -0
  48. package/docs/troubleshooting.md +963 -0
  49. package/package.json +69 -5
@@ -0,0 +1,351 @@
1
+ # The typed context
2
+
3
+ This page covers what a resolver reads as its context — graxia's, the app's,
4
+ and what the `context` option adds — how to type a schema with it, and the
5
+ compile error when the schema reads what the app does not build.
6
+
7
+ ```ts
8
+ import { alxia } from '@softistx/alxia';
9
+ import { graphql, type GraphQLContext } from '@softistx/alxia-graphql';
10
+ import { createSchema } from '@softistx/graxia';
11
+
12
+ const users = new Map([['1', { id: '1', name: 'Ada' }]]);
13
+
14
+ const base = alxia()
15
+ .decorate({ users })
16
+ .derive(({ request }) => ({ viewer: request.headers.get('x-user') }));
17
+
18
+ const schema = createSchema<GraphQLContext<typeof base>>()({
19
+ typeDefs: /* GraphQL */ `
20
+ type User { id: ID!, name: String! }
21
+ type Query { me: String, user(id: ID!): User }
22
+ `,
23
+ resolvers: {
24
+ Query: {
25
+ me: (_, __, { viewer }) => viewer, // string | null
26
+ user: (_, { id }: { id: string }, { users }) => users.get(id) ?? null,
27
+ },
28
+ },
29
+ });
30
+
31
+ const app = base.plugin((app) => graphql(app, { schema }));
32
+ ```
33
+
34
+ Declare the middlewares on a `base` app, type the schema with
35
+ `GraphQLContext<typeof base>`, then mount the endpoint on it. The schema
36
+ cannot be typed from `app` itself: `app` is built from the schema.
37
+
38
+ ## `GraphQLContext`
39
+
40
+ ```ts
41
+ type GraphQLContext<App, UserContext = Empty> =
42
+ CoreContext & ServerContext<ContextOf<App>> & GraphQLWsContext & UserContext;
43
+ // when App is not an alxia app — a function returning one, a schema, a route:
44
+ // { readonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>' }
45
+
46
+ type ServerContext<Ctx> = Omit<
47
+ BaseContext & Ctx,
48
+ 'params' | 'query' | 'headers' | 'cookies' | 'body' | 'reply' | 'redirect'
49
+ >;
50
+ ```
51
+
52
+ Given anything but an app's type, the context holds only that message, so
53
+ the first resolver that reads a field is a compile error naming it:
54
+
55
+ ```text
56
+ error TS2339: Property 'viewer' does not exist on type '{ readonly '~error': "GraphQLContext needs the type of an app: GraphQLContext<typeof app>"; } & GraphQLWsContext'.
57
+ ```
58
+
59
+ Give it the app's type, `typeof base` — not that of a function that builds
60
+ the app, nor of a schema
61
+ ([Troubleshooting](../troubleshooting.md#property-viewer-does-not-exist-on-type--readonly-error-graphqlcontext-needs-the-type-of-an-app-graphqlcontexttypeof-app---graphqlwscontext)).
62
+
63
+ A resolver's context holds:
64
+
65
+ | From | Fields |
66
+ | --- | --- |
67
+ | graxia (`CoreContext`) | `signal`: the operation's `AbortSignal`, aborted when the client leaves, the stream ends or the server shuts down |
68
+ | the app's middlewares | everything `decorate` and `derive` added before the endpoint, and what middlewares such as `@softistx/alxia-jwt`'s `bearer` add (`user`) |
69
+ | the route (`BaseContext`) | `request`, `url`, `ip`, `server`, `route`, `pathParams`, `error`, and `set` |
70
+ | a WebSocket operation (`GraphQLWsContext`) | `connectionParams`, the client's, when the operation came over `ws` |
71
+ | the `context` option | what it returns, as `UserContext` ([below](#the-context-option)) |
72
+
73
+ What a route handler reads but a resolver does not: `params`, `query`,
74
+ `headers`, `cookies` and `body` are the route's, read through `request`;
75
+ `reply` and `redirect` answer a route, not a field. The request, params,
76
+ headers and cookies are not spread into the context any more. A resolver
77
+ that reads one is a compile error:
78
+
79
+ ```text
80
+ error TS2339: Property 'query' does not exist on type 'CoreContext & ServerContext<…> & GraphQLWsContext & Empty'.
81
+ ```
82
+
83
+ Read a header or a cookie from `request`:
84
+
85
+ ```ts
86
+ const locale = (_: unknown, __: unknown, { request }: GraphQLContext<typeof base>) =>
87
+ request.headers.get('accept-language') ?? 'en';
88
+ ```
89
+
90
+ ## Setting a header or a cookie
91
+
92
+ `set` is the route's: what a resolver sets on it is on the response, beside
93
+ graxia's own headers. A header a resolver sets is lost on a server-sent
94
+ events or multipart response, whose headers left before the resolver ran, and
95
+ `set` is ignored over a WebSocket.
96
+
97
+ ```ts
98
+ const schema = createSchema<GraphQLContext<typeof base>>()({
99
+ typeDefs: /* GraphQL */ `type Query { ok: Boolean } type Mutation { login(name: String!): Boolean! }`,
100
+ resolvers: {
101
+ Mutation: {
102
+ login: (_, { name }: { name: string }, { set }) => {
103
+ set.cookies.set('session', name, { httpOnly: true, sameSite: 'lax' });
104
+ set.headers.set('cache-control', 'no-store');
105
+ return true;
106
+ },
107
+ },
108
+ },
109
+ });
110
+ ```
111
+
112
+ `set.cookies` is a `Bun.CookieMap`: each `set` or `delete` is a
113
+ `Set-Cookie` header. `set.headers` is a `Headers`.
114
+
115
+ ## The compile check
116
+
117
+ graxia's types alone accept any schema. `graphql` also checks that the
118
+ context the app builds holds what the schema's resolvers read. A schema
119
+ typed with a context the app does not build is refused, and the error names
120
+ the missing field:
121
+
122
+ ```ts
123
+ const app = alxia().plugin((app) => graphql(app, { schema })); // no middleware derives `viewer` or `users`
124
+ ```
125
+
126
+ ```text
127
+ error TS2322: Type 'GraphQLSchemaWithContext<…>' is not assignable to type 'GraphQLSchema & { _context?: … } & ("the schema's resolvers read a context the app does not build: missing users" | "the schema's resolvers read a context the app does not build: missing viewer")'.
128
+ …
129
+ Type 'GraphQLSchemaWithContext<…>' is not assignable to type '"the schema's resolvers read a context the app does not build: missing viewer"'.
130
+ ```
131
+
132
+ With `exactOptionalPropertyTypes` on, the code is `TS2375`; the message
133
+ ends the same way. The fix is to mount the endpoint on the
134
+ app the schema was typed from, after its middlewares:
135
+ [Troubleshooting](../troubleshooting.md#the-schemas-resolvers-read-a-context-the-app-does-not-build-missing-).
136
+
137
+ An untyped schema — `createSchema({ … })` with no type argument — passes
138
+ on any app, but its resolvers see graxia's context only: reading `viewer`
139
+ there is `Property 'viewer' does not exist`. Type the schema to read the
140
+ app's context.
141
+
142
+ ## With a token: `@softistx/alxia-jwt`
143
+
144
+ A guard is a middleware like any other, given to `use` before the endpoint. With `@softistx/alxia-jwt`'s `bearer`, the
145
+ endpoint requires a token and `user` is the token's claims, typed by the
146
+ schema you give it:
147
+
148
+ ```ts
149
+ import { alxia } from '@softistx/alxia';
150
+ import { graphql, type GraphQLContext, type GraphQLContextInit } from '@softistx/alxia-graphql';
151
+ import { bearer, createJwt } from '@softistx/alxia-jwt';
152
+ import { createSchema } from '@softistx/graxia';
153
+ import { z } from 'zod';
154
+
155
+ const jwt = createJwt({ secret: Bun.env['JWT_SECRET']! });
156
+ const Claims = z.object({ sub: z.string(), role: z.enum(['admin', 'user']) });
157
+
158
+ const base = alxia().use(bearer({ jwt, schema: Claims })); // 401 without a valid token
159
+
160
+ const schema = createSchema<GraphQLContext<typeof base>>()({
161
+ typeDefs: /* GraphQL */ `type Query { me: String!, isAdmin: Boolean! }`,
162
+ resolvers: {
163
+ Query: {
164
+ me: (_, __, { user }) => user.sub, // user: { sub: string; role: 'admin' | 'user' }
165
+ isAdmin: (_, __, { user }) => user.role === 'admin',
166
+ },
167
+ },
168
+ });
169
+
170
+ const app = base.plugin((app) => graphql(app, { schema }));
171
+ ```
172
+
173
+ The guard's `401` and its body are `@softistx/alxia-jwt`'s, described in its
174
+ [bearer guard guide](https://github.com/softistx/alxia/blob/develop/packages/jwt/docs/guide/bearer-guard.md).
175
+
176
+ ## The `context` option
177
+
178
+ The `context` option adds to the context per request. Its argument is
179
+ graxia's `ContextInit`: the `request`, the `signal` and the `serverContext`,
180
+ which is what the app's middlewares built. What it returns is merged in
181
+ (graxia's `onContext` hook, which a plugin implements, does the same).
182
+ Give the type of what it returns to `GraphQLContext` as the second argument:
183
+
184
+ ```ts
185
+ type Loaders = { loaders: { user: (id: string) => Promise<User | null> } };
186
+
187
+ const schema = createSchema<GraphQLContext<typeof base, Loaders>>()({
188
+ typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Query { user(id: ID!): User }`,
189
+ resolvers: {
190
+ Query: { user: (_, { id }: { id: string }, { loaders }) => loaders.user(id) },
191
+ },
192
+ });
193
+
194
+ const app = base.plugin((app) =>
195
+ graphql(app, {
196
+ schema,
197
+ // annotate the argument: see below
198
+ context: ({ serverContext }: GraphQLContextInit<typeof base>) => ({
199
+ loaders: { user: async (id: string) => serverContext.users.get(id) ?? null },
200
+ }),
201
+ }),
202
+ );
203
+ ```
204
+
205
+ Without the `context` option, the same schema is refused: the error ends in
206
+ `missing loaders`.
207
+
208
+ **Annotate the argument when the function reads it** with `GraphQLContextInit<typeof base>` (the `ContextInit` of the app's `serverContext`, no `['~context']` to write). TypeScript infers
209
+ `UserContext` from what the function returns only when the function does
210
+ not depend on its parameter's contextual type. `({ serverContext }) => …`
211
+ unannotated leaves `UserContext` as `Empty`, and the schema is refused
212
+ with `missing loaders` although the function returns them. A function that
213
+ takes no argument, or annotates it, is inferred:
214
+
215
+ ```ts
216
+ context: () => ({ loaders: createLoaders() }), // inferred
217
+ context: ({ serverContext }: GraphQLContextInit<typeof base>) => ({ loaders: …(serverContext.users) }), // inferred
218
+ context: ({ serverContext }) => ({ loaders: …(serverContext.users) }), // `missing loaders`
219
+ ```
220
+
221
+ Prefer a `derive` on the app for what every route needs — the user, a
222
+ database handle — and the `context` option for what only resolvers do, such
223
+ as per-request data loaders.
224
+
225
+ ## Batching with DataLoader (N+1)
226
+
227
+ A field that loads a record for each parent, `Note.author` over a list of
228
+ notes, runs a query per parent: 50 notes, 51 queries. A
229
+ [DataLoader](https://github.com/graphql/dataloader) collects the `load` calls
230
+ of one tick and calls your batch function once. Build the loaders in the
231
+ `context` option, so each request has its own, and type them through
232
+ `GraphQLContext`'s second argument, so every resolver reads `loaders` typed:
233
+
234
+ ```sh
235
+ bun add dataloader
236
+ ```
237
+
238
+ ```ts
239
+ import DataLoader from 'dataloader';
240
+
241
+ // `findUsers` is your batch query: one result per id, in the order of the ids.
242
+
243
+ const createLoaders = () => ({
244
+ user: new DataLoader(async (ids: readonly string[]) => findUsers(ids)), // one query for all ids
245
+ });
246
+ type Loaders = ReturnType<typeof createLoaders>;
247
+ type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
248
+
249
+ const schema = createSchema<Context>()({
250
+ typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Note { author: User! } type Query { notes: [Note!]! }`,
251
+ resolvers: { Note: { author: (note: { authorId: string }, _, { loaders }) => loaders.user.load(note.authorId) } },
252
+ });
253
+
254
+ const app = base.plugin((app) =>
255
+ graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }),
256
+ );
257
+ ```
258
+
259
+ **The loaders must be per request.** A DataLoader caches every key it loads.
260
+ Created once, at module level or with `decorate`, its cache outlives the
261
+ request: it keeps serving a record after an update, grows for the life of the
262
+ process, and a loader that reads with the viewer's permissions hands one
263
+ user's data to the next. Per request, the cache lives and dies with one
264
+ response, and the same user loaded twice in it is one lookup.
265
+
266
+ The [GraphQL recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md)
267
+ builds this step by step, with a spec that counts the calls to the store: five notes, one batch.
268
+
269
+ ## One value per request
270
+
271
+ Not every shared value is a loader built in `context`. A loader for a
272
+ rarely used field, or any value that twenty resolvers of one response need
273
+ (the category of each item, the viewer's permissions), is better built on
274
+ first use. `oncePerRequest(request, key, load)` does that: the first call for
275
+ a request and a `key` runs `load`, every later call returns the same value.
276
+
277
+ ```ts
278
+ import DataLoader from 'dataloader';
279
+ import { oncePerRequest } from '@softistx/alxia-graphql';
280
+
281
+ const categoryLoader = (context: object) =>
282
+ oncePerRequest(
283
+ context,
284
+ 'categories',
285
+ () => new DataLoader(async (ids: readonly string[]) => findCategories(ids)),
286
+ );
287
+
288
+ const resolvers = {
289
+ Item: {
290
+ category: (item: { categoryId: string }, _args: unknown, context: object) =>
291
+ categoryLoader(context).load(item.categoryId),
292
+ },
293
+ };
294
+ ```
295
+
296
+ Points to know:
297
+
298
+ - `request` is any object that lives for one request: pass the resolvers'
299
+ context. The cache is a `WeakMap` keyed by it, so it is released when the
300
+ context is, and two requests never share a value. Over WebSocket, `context`
301
+ runs for each operation, so a value lasts one operation.
302
+ - The key names the value inside a request. Two different values under one key
303
+ are one value: give each its own key.
304
+ - `load` may return a promise. Concurrent callers share that one promise. If it
305
+ throws or rejects, nothing is kept and the next call loads again.
306
+ - A `DataLoader` per request and key needs nothing from the package:
307
+ `dataloader` is not a dependency, and the type of the loader is the type
308
+ `load` returns, so `.load(id)` is typed.
309
+
310
+ ### A mutation's root fields
311
+
312
+ A mutation operation runs its root fields one after another in one request,
313
+ and one may change what a later one reads: `updateDepartment` then
314
+ `updateWard { department { name } }` must show the new name, but the
315
+ department read before the update is in the request's cache.
316
+ `clearRequestCache(request)` forgets everything `oncePerRequest` kept for that
317
+ request, and `freshPerMutation(resolvers)` calls it before every function of
318
+ `Mutation`:
319
+
320
+ ```ts
321
+ import { freshPerMutation } from '@softistx/alxia-graphql';
322
+
323
+ const resolvers = freshPerMutation({
324
+ Query: { /* one cache for the whole request */ },
325
+ Mutation: {
326
+ updateDepartment: async (_p, args, context) => { /* … */ },
327
+ updateWard: async (_p, args, context) => { /* … */ },
328
+ },
329
+ Ward: {
330
+ // shares the cache of the root field that returned the ward
331
+ department: (ward, _args, context) => departmentLoader(context).load(ward.departmentId),
332
+ },
333
+ });
334
+ ```
335
+
336
+ Given an array of maps (what `createSchema`'s `resolvers` accepts), it returns
337
+ an array: each map is wrapped on its own and graxia merges them afterwards.
338
+
339
+ - Each root mutation field starts with an empty cache; its sub-fields share
340
+ it. A query has no wrapped field, so it keeps one cache.
341
+ - Only functions of `Mutation` are wrapped; other types and non-function
342
+ entries are returned as they are, and the wrapped field's result is
343
+ unchanged. The context must be an object (it always is).
344
+ - A call to `oncePerRequest` already in flight when the cache is cleared keeps
345
+ its own value; only later calls load again.
346
+
347
+ ## See also
348
+
349
+ - [Mounting the endpoint](endpoint.md): which middlewares run before it.
350
+ - [Middlewares](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md),
351
+ in `@softistx/alxia`'s guide: `decorate` and `derive`.
@@ -0,0 +1,293 @@
1
+ # Mounting the endpoint
2
+
3
+ This page covers `graphql(app, options)`: where the endpoint is served, what
4
+ it answers, which middlewares run before it, and how to test it.
5
+
6
+ ```ts
7
+ import { alxia } from '@softistx/alxia';
8
+ import { graphql } from '@softistx/alxia-graphql';
9
+ import { createSchema } from '@softistx/graxia';
10
+
11
+ const schema = createSchema()({
12
+ typeDefs: /* GraphQL */ `type Query { hello: String! }`,
13
+ resolvers: { Query: { hello: () => 'world' } },
14
+ });
15
+
16
+ const app = alxia()
17
+ .get('/health', ({ reply }) => reply(200, 'ok'))
18
+ .plugin((app) => graphql(app, { schema })); // GET and POST /graphql
19
+
20
+ app.listen(3000);
21
+ ```
22
+
23
+ ```sh
24
+ curl localhost:3000/graphql -H 'content-type: application/json' -d '{"query":"{ hello }"}'
25
+ # {"data":{"hello":"world"}}
26
+ ```
27
+
28
+ ## `graphql`
29
+
30
+ ```ts
31
+ function graphql<Ctx, Prefix, SchemaCtx, UserCtx = Empty, const Path = '/graphql'>(
32
+ app: Alxia<Ctx, Prefix>,
33
+ options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx>,
34
+ ): Alxia<Ctx, Prefix>;
35
+ ```
36
+
37
+ `graphql` declares a `GET` and a `POST` route at `path` on `app`, and returns
38
+ `app`, its type unchanged. Hand it to `app.plugin` as a function, so
39
+ it stays in the chain and sees the app as typed so far:
40
+
41
+ ```ts
42
+ const app = base.plugin((app) => graphql(app, { schema }));
43
+ ```
44
+
45
+ Calling it directly does the same: `graphql(base, { schema })` declares the
46
+ routes on `base` and returns it.
47
+
48
+ ### Options
49
+
50
+ | Option | Type | Default | Effect |
51
+ | --- | --- | --- | --- |
52
+ | `schema` | `GraphQLSchemaWithContext<SchemaCtx>` | — | The schema, from graxia's `createSchema` (`@softistx/graxia`) or any tool that types its context. Its context is checked against the app's: see [The typed context](context.md). |
53
+ | `path` | `` `/${string}` `` | `'/graphql'` | Where the endpoint is, under the app's prefix. |
54
+ | `ide` | `'graphiql' \| 'apollo-sandbox' \| false` | GraphiQL in dev (`isDev`), none otherwise | What a browser gets at the endpoint: see [GraphiQL and Apollo Sandbox](ide.md). |
55
+ | `graphiql` | `GraphiQLOptions` of `@softistx/graxia-graphiql` | graxia's | GraphiQL's options, when `ide` is `'graphiql'`. |
56
+ | `sandbox` | `SandboxOptions` | — | Apollo Sandbox's options, when `ide` is `'apollo-sandbox'`. |
57
+ | `ws` | `boolean \| { path?, keepAlive? }` | `false` | GraphQL over WebSocket too, served by graxia, no extra install: see [GraphQL over WebSocket](websockets.md). |
58
+ | `limits` | `{ tokens?, nesting?, bodyBytes? }` | `tokens: 15_000`, `nesting: 1_000` | `tokens` is the most tokens a document may hold and `nesting` the most levels of `{`, `(` and `[`; a longer or deeper one is refused as `GRAPHQL_PARSE_FAILED` before the parser recurses into it. `false` for no cap. Replaces `maxTokens` and `maxNesting`, which still work but are deprecated; a bad value is not rejected where `graphql()` is declared: see [Cap what a request costs](production.md#cap-what-a-request-costs). |
59
+ | `caches` | `false \| { parse?: { maxBytes?, max?, ttlMs? } \| false }` | `parse: { maxBytes: 64 MiB, max: 1_024 }` | The cache of parsed documents, bounded by the estimated bytes of its sources (`maxBytes`), its entries and their age. `false` parses every request. Replaces `parseCache`, which still maps (`maxBytes`, `max`, `ttl`). |
60
+ | `bodyLimit` | `number` | the app's earlier `bodyLimit()`, else `1_048_576` (1 MiB) | The most bytes a `POST` body may hold: graxia's `limits.bodyBytes`. Past it graxia answers `413` with `extensions.code: 'BODY_TOO_LARGE'`, whether the size is declared or counted. A positive whole number of bytes, else a `GraxiaConfigError` (it extends `Error`) with the message `limits.bodyBytes must be a positive integer`, thrown where `graphql()` is declared, before any route. A `multipart` upload needs a larger one: see [Cap what a request costs](production.md#cap-what-a-request-costs). |
61
+ | `cors`, `logging`, `requestId` | removed | — | Throw a `TypeError` naming the fix: `@softistx/alxia-cors` for CORS, graxia's `onUnexpected` and `@softistx/alxia-logger` for logs, graxia's `x-request-id` for the id: see [troubleshooting](../troubleshooting.md#graphqlapp--logging--requestid-or-cors-throws-a-typeerror). |
62
+ | `telemetry` | graxia's `telemetry` option | `{ operationSpans: false }` | graxia makes no operation span of its own, so `@softistx/alxia-telemetry`'s is the operation's only one; graxia's parse, validate and execute spans nest under it. `false` turns graxia's telemetry off altogether: see [graxia's own spans](#graxias-own-spans). |
63
+ | every other option | | graxia's | `plugins`, `context`, `maskErrors`, `batching`… given to graxia's `createGraxia`, which this package wraps: see [Plugins and options](plugins.md). |
64
+
65
+ `graphqlEndpoint` is not an option: `path` sets it.
66
+
67
+ ## Where it is served
68
+
69
+ `path` is joined to the app's prefix, and to the prefix of every app it is
70
+ mounted into:
71
+
72
+ ```ts
73
+ import { alxia } from '@softistx/alxia';
74
+
75
+ const api = alxia({ prefix: '/api' })
76
+ .plugin((app) => graphql(app, { schema, path: '/gql' })); // /api/gql
77
+
78
+ const root = alxia({ prefix: '/v1' }).plugin(api); // /v1/api/gql
79
+
80
+ root.routes.map((route) => `${route.method} ${route.path}`); // ['GET /v1/api/gql', 'POST /v1/api/gql']
81
+ ```
82
+
83
+ Two endpoints on one app need two paths: declaring the default path twice
84
+ throws `GET /graphql is declared twice` when the app is built. Give each its
85
+ own path:
86
+
87
+ ```ts
88
+ const app = alxia()
89
+ .plugin((app) => graphql(app, { schema }))
90
+ .plugin((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
91
+ ```
92
+
93
+ ## Behind the app's middlewares
94
+
95
+ The endpoint is a route like any other: every middleware given to `use`
96
+ **before** it runs first, and one that replies ends the request there. A
97
+ guard before it guards it — a plain `(ctx, next)` function, what it passes
98
+ `next` typed into each resolver's context:
99
+
100
+ ```ts
101
+ const app = alxia()
102
+ .use(({ request, reply }, next) =>
103
+ request.headers.get('authorization') === `Bearer ${Bun.env['API_TOKEN']}`
104
+ ? next({ viewer: 'service' })
105
+ : reply(401, { error: 'unauthorized' as const }),
106
+ )
107
+ .plugin((app) => graphql(app, { schema })); // 401 without the token
108
+ ```
109
+
110
+ `@softistx/alxia-jwt`'s `bearer()` is that guard for a JWT: `.use(bearer({ jwt }))`
111
+ ([The typed context](context.md#with-a-token-softistxalxia-jwt)).
112
+
113
+ A middleware declared **after** `app.plugin` does not run for the endpoint: it
114
+ answers without it. Give the observers (`@softistx/alxia-logger`, `@softistx/alxia-cors`,
115
+ `@softistx/alxia-secure-headers`, `@softistx/alxia-compress`) to `use` first, so they wrap the
116
+ endpoint, and every other request, the 404s included:
117
+
118
+ ```ts
119
+ import { alxia } from '@softistx/alxia';
120
+ import { cors } from '@softistx/alxia-cors';
121
+ import { graphql } from '@softistx/alxia-graphql';
122
+ import { logger } from '@softistx/alxia-logger';
123
+ import { secureHeaders } from '@softistx/alxia-secure-headers';
124
+
125
+ const app = alxia()
126
+ .use(logger())
127
+ .use(secureHeaders())
128
+ .use(cors({ origin: 'https://app.example.com' }))
129
+ .plugin((app) => graphql(app, { schema }));
130
+ ```
131
+
132
+ A guard given to the app's `use` (`bearer`, a required session) also runs on
133
+ a request no route matches: an anonymous request to a missing path is a 401,
134
+ not a 404. The order is core's, explained in
135
+ [Middlewares](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md).
136
+
137
+ What the middlewares added is in each resolver's context: that is the next page,
138
+ [The typed context](context.md).
139
+
140
+ ## What it answers
141
+
142
+ graxia answers the request; the package passes its status, headers and body
143
+ through as the route's reply, and adds a `Content-Security-Policy` to an
144
+ IDE page ([GraphiQL and Apollo Sandbox](ide.md)).
145
+
146
+ | Request | Answer |
147
+ | --- | --- |
148
+ | `POST` with `{"query": …}` | `200` and `{"data": …}`, with `errors` beside it when a resolver failed |
149
+ | `GET ?query=…` | the same, for a query; a mutation is a `405` |
150
+ | `POST` a subscription with `Accept: text/event-stream` | `200`, a `text/event-stream` of results ([subscriptions](plugins.md#subscriptions)) |
151
+ | a WebSocket upgrade offering `graphql-transport-ws`, `ws` on | `101`, then queries, mutations and subscriptions over the socket ([GraphQL over WebSocket](websockets.md)); with `ws` off, no `101` |
152
+ | `GET` from a browser (`Accept: text/html`), no `query` | the IDE page; with `ide: false`, a GraphQL answer (`Must provide a query string.`) |
153
+ | a middleware replied first | that middleware's reply, such as a `401` |
154
+
155
+ ```text
156
+ POST {"query":"{ nope }"} → 200 {"errors":[{"message":"Cannot query field \"nope\" on type \"Query\".", … "extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}
157
+ GET ?query=mutation { m } → 405 {"errors":[{"message":"Can only perform a mutation operation from a POST request.","extensions":{"code":"BAD_REQUEST"}}]}
158
+ POST {} → 200 {"errors":[{"message":"Must provide query string.","extensions":{"code":"BAD_REQUEST"}}]}
159
+ ```
160
+
161
+ Both methods answer a body to read as GraphQL, whatever its status, and
162
+ the replies of the middlewares before them — a guard's `401`, say.
163
+
164
+ ## The operation in the log and the trace
165
+
166
+ Every call is a `POST /graphql`, so the route alone cannot tell `GetNotes`
167
+ from `AddNote`. For each operation graxia executes or subscribes to,
168
+ `graphql()` reports its type and name to the middlewares around it
169
+ (`reportOperation` of `@softistx/alxia`, a graxia plugin it adds after yours),
170
+ and no package imports another: `@softistx/alxia-logger` adds `operationName` and
171
+ `operationType` to the request's line, and `@softistx/alxia-telemetry` names its
172
+ span `query GetNotes` with `graphql.operation.name` and
173
+ `graphql.operation.type`. Give both to `use` before `graphql()`:
174
+
175
+ ```ts
176
+ const app = alxia()
177
+ .use(logger())
178
+ .use(telemetry({ service: 'notes' }))
179
+ .plugin((app) => graphql(app, { schema }));
180
+ ```
181
+
182
+ ```json
183
+ {"message":"POST /graphql 200","status":200,"operationName":"GetNotes","operationType":"query"}
184
+ ```
185
+
186
+ - A batched body (`batching`, an array) is one line and one span: the type
187
+ is `batch`, the names are listed, `GetNotes,AddNote`.
188
+ - An anonymous operation has a type and no name.
189
+ - A request refused before it executes (a syntax error, a document that
190
+ fails validation) names no operation: its line is the plain
191
+ `POST /graphql`.
192
+ - Your own middleware reads it with `operationOf(ctx)` after `next()`.
193
+ - Over `ws: true`, each operation on a socket is a line and a span of its
194
+ own, told to the observers around the upgrade
195
+ ([WebSocket guide](websockets.md#logging-and-tracing)).
196
+
197
+ ### graxia's own spans
198
+
199
+ `graphql()` sets graxia's `telemetry` to `{ operationSpans: false }`, over
200
+ HTTP and over a WebSocket alike. graxia then makes no request or operation
201
+ span of its own, so `@softistx/alxia-telemetry`'s span is the operation's only one,
202
+ and its step spans (`graphql.parse`, `graphql.validate`, `graphql.execute`)
203
+ are children of that span, which is active when the request arrives. With
204
+ no span active (no `@softistx/alxia-telemetry` in front), graxia spans the request
205
+ and the operation itself, as usual. Pass `telemetry: { resolverSpans: true }`
206
+ (or any other graxia telemetry option) to add resolver spans: the
207
+ `operationSpans: false` default stays under the object you pass, and
208
+ `operationSpans: true` brings graxia's operation span back (and doubles
209
+ `@softistx/alxia-telemetry`'s). `telemetry: false` turns graxia's telemetry off
210
+ altogether, step spans included. See graxia's telemetry guide for the options.
211
+
212
+ ## Errors, health and shutdown
213
+
214
+ **GraphQL errors stay GraphQL's.** A resolver that throws, a query that
215
+ does not validate, is an entry of `errors[]` in graxia's answer — inside a
216
+ `200`, as the GraphQL over HTTP specification has it — whatever
217
+ `@softistx/alxia`'s `errors` option says. `alxia({ errors: 'problem' })`
218
+ applies to the HTTP layer around the endpoint: `@softistx/alxia-jwt`'s 401 before
219
+ it, a middleware's 500, a `PUT` at its
220
+ path (405) — each an `application/problem+json` problem. A refusal graxia
221
+ builds (a body past `bodyLimit` is `413 BODY_TOO_LARGE`) keeps graxia's JSON
222
+ format and its `extensions.code`
223
+ ([core's errors guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/errors.md#graphql)).
224
+
225
+ ```text
226
+ POST {"query":"{ boom }"} → 200 {"data":{"boom":null},"errors":[{"message":"Unexpected error.", …}]}
227
+ POST without a token → 401 application/problem+json {"type":"about:blank","title":"Unauthorized", …}
228
+ ```
229
+
230
+ **Probes and the drain.** `@softistx/alxia`'s `health()` mounts beside the
231
+ endpoint, and `listen`'s graceful shutdown covers it: on `SIGTERM` a
232
+ query or a mutation in flight is answered, and a subscription over
233
+ server-sent events ends — its stream cancelled as when the client leaves,
234
+ the client reading the end and reconnecting elsewhere — so the drain does
235
+ not wait for it until `shutdownTimeout`.
236
+
237
+ ```ts
238
+ import { alxia, health } from '@softistx/alxia';
239
+ import { bearer } from '@softistx/alxia-jwt';
240
+ import { graphql } from '@softistx/alxia-graphql';
241
+
242
+ const app = alxia({ errors: 'problem' })
243
+ .plugin(health({ checks: { db: () => sql`select 1` } }))
244
+ .use(bearer({ jwt }))
245
+ .plugin((app) => graphql(app, { schema }));
246
+
247
+ app.listen({ port: 4000 }); // SIGTERM: /ready 503, queries answered, subscriptions ended, exit 0
248
+ ```
249
+
250
+ ## Testing it
251
+
252
+ The endpoint runs in process through `app.fetch`, like every alxia route:
253
+ no server, no port. `graphqlClient` from `@softistx/alxia-graphql/testing` sends the
254
+ operation and reads the answer; graxia writes nothing to the console for a request, and
255
+ reports unexpected failures through `onUnexpected`.
256
+
257
+ ```ts
258
+ import { describe, expect, test } from 'bun:test';
259
+ import { alxia } from '@softistx/alxia';
260
+ import { graphql } from '@softistx/alxia-graphql';
261
+ import { graphqlClient } from '@softistx/alxia-graphql/testing';
262
+ import { createSchema } from '@softistx/graxia';
263
+
264
+ const schema = createSchema()({
265
+ typeDefs: /* GraphQL */ `type Query { hello(name: String!): String! }`,
266
+ resolvers: { Query: { hello: (_, { name }: { name: string }) => `hello ${name}` } },
267
+ });
268
+
269
+ const app = alxia().plugin((app) => graphql(app, { schema }));
270
+
271
+ describe('graphql', () => {
272
+ test('hello', async () => {
273
+ const { data } = await graphqlClient(app).query(
274
+ 'query ($name: String!) { hello(name: $name) }',
275
+ { variables: { name: 'Ada' } },
276
+ );
277
+ expect(data).toEqual({ hello: 'hello Ada' });
278
+ });
279
+ });
280
+ ```
281
+
282
+ Headers, a custom path, typed documents and the HTTP status are in
283
+ [Testing the endpoint](testing.md).
284
+
285
+ ## See also
286
+
287
+ - [The typed context](context.md): what a resolver reads, and the compile
288
+ error when the app does not build it.
289
+ - [Plugins and options](plugins.md): plugins, errors, subscriptions,
290
+ CORS.
291
+ - [GraphiQL and Apollo Sandbox](ide.md): the page a browser gets.
292
+ - [GraphQL over WebSocket](websockets.md): `ws`, for `graphql-ws`
293
+ clients.