@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,374 @@
1
+ # Harden a GraphQL API for production
2
+
3
+ A GraphQL endpoint mounted as in [the endpoint guide](endpoint.md) works. What a GraphQL API exposed to the internet also
4
+ needs is not in a schema: one request can ask for a great deal, nothing says
5
+ who may ask how often, and the defaults that help a developer help an
6
+ attacker. Seven points, each a few lines, from the
7
+ [GraphQL API recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md),
8
+ whose files they are (`src/context.ts` holds the base, which each app builds on with `base.fork()`). Add the packages the snippets use:
9
+
10
+ ```sh
11
+ bun add @softistx/alxia-rate-limit
12
+ ```
13
+
14
+ ## Rate limit the endpoint
15
+
16
+ `@softistx/alxia-rate-limit` goes to `use` before the endpoint, and counts the
17
+ requests to it. Key it by the viewer, so one user's allowance is theirs
18
+ wherever they connect from, and by the client's address for an anonymous
19
+ request. Behind a proxy, the address is the proxy's unless the app reads the
20
+ header it appends to, with core's `forwardedIp`, which never believes the
21
+ entries the client wrote (the recipe's base reads the number of proxies from
22
+ `PROXY_HOPS`):
23
+
24
+ ```ts
25
+ import { alxia, forwardedIp } from '@softistx/alxia';
26
+
27
+ const base = alxia({ ip: forwardedIp({ trusted: 1 }) }); // one proxy in front
28
+ ```
29
+
30
+ ```ts no-check
31
+ // file: src/limits.ts
32
+ import { rateLimit } from '@softistx/alxia-rate-limit';
33
+ import type { UserRecord } from './store';
34
+
35
+ // What is counted: the viewer's id, else the client's address. `undefined`
36
+ // is not counted: with no address (a request made in process, with no
37
+ // socket) there is nothing to count.
38
+ export const keyOf = ({ viewer, ip }: { viewer: UserRecord | null; ip: string | undefined }) =>
39
+ viewer ? `user:${viewer.id}` : ip && `ip:${ip}`;
40
+
41
+ // `max` requests a minute for each key. Past it, a 429 with `Retry-After`.
42
+ export const limitTo = (max: number) =>
43
+ rateLimit<{ viewer: UserRecord | null }>({ limit: max, windowMs: 60_000, key: keyOf });
44
+ ```
45
+
46
+ **One HTTP request is not one operation.** A client may send an array of
47
+ operations in a single `POST` when `batching` is on, and a document may ask
48
+ for a hundred fields, or the same expensive field a hundred times under
49
+ aliases. The limit counts the request: keep `batching` off, or give it a
50
+ small `limit`, and count the fields that matter with the next point.
51
+
52
+ ## Count a field, not a request
53
+
54
+ A sign-in selected 300 times under aliases is one HTTP request and 300
55
+ credential guesses. `fieldRateLimit` counts every selection of the fields you
56
+ name (aliases, inline fragments and fragment spreads expanded; a fragment
57
+ spread twice counts twice) and consumes that cost on a limit keyed by the
58
+ client, before the operation runs.
59
+
60
+ ```ts
61
+ // file: src/field-limits.ts
62
+ import { fieldRateLimit, limitFromStore } from '@softistx/alxia-graphql';
63
+ import { MemoryStore } from '@softistx/alxia-rate-limit';
64
+
65
+ const store = new MemoryStore();
66
+
67
+ // `signIn` selected N times costs N: 5 a minute for each client address.
68
+ export const fieldLimits = fieldRateLimit({
69
+ code: 'TOO_MANY_ATTEMPTS', // optional: RATE_LIMITED by default
70
+ fields: {
71
+ signIn: {
72
+ limit: limitFromStore(store, { limit: 5, windowMs: 60_000 }),
73
+ single: true, // and a document writing it twice is refused outright
74
+ },
75
+ },
76
+ });
77
+ ```
78
+
79
+ Give it to `graphql(app, { plugins: [fieldLimits] })`, **first** in the list.
80
+ The check runs in the plugin's `onExecute`, so a plugin after it that replaces
81
+ the execute function does not drop it, but a plugin before it that does would
82
+ change what it sees. Past the limit the operation does not run: a 429 whose
83
+ error has `code: 'RATE_LIMITED'` and `extensions.retryAfter` in seconds, with
84
+ the `Retry-After` header. A field with `single: true` written more than once
85
+ (a selection reached twice with the same response key and arguments counts
86
+ once) is a 400 `FIELD_SELECTED_ONCE`, and nothing is consumed.
87
+
88
+ | Option | Default | Effect |
89
+ | --- | --- | --- |
90
+ | `fields` | required | field name (at any depth) to its limit, or `{ limit, single? }` |
91
+ | `key` | `ctx.ip` | who is counted, from the context; `undefined` counts nothing (a call in process has no address) |
92
+ | `ipv6Prefix` | none | the default key becomes the IPv6 network of `ctx.ip`, its first `ipv6Prefix` bits (0 to 128), as in [`rateLimit`](https://github.com/softistx/alxia/blob/develop/packages/rate-limit/docs/guide.md#ipv6prefix); throws with a `key` |
93
+ | `code` | `RATE_LIMITED` | the `extensions.code` of the over-limit refusal |
94
+
95
+ A limit is any `{ consume(key, cost) }` answering `{ allowed, retryAfter }`
96
+ (milliseconds). The key it receives is `<field>:<client>`, so two fields never
97
+ share a count. Two ways to build one:
98
+
99
+ ```ts no-check
100
+ // An @softistx/alxia-rate-limit store (the memory store, or redisStore for many processes):
101
+ // one consume per unit of cost, stopped at the first refusal. A store that
102
+ // declares its own policy needs none here, and one that differs is an error.
103
+ const fromStore = limitFromStore(store, { limit: 5, windowMs: 60_000 });
104
+
105
+ // A @softistx/redis bound limit, which takes the cost itself. `handle` is the
106
+ // wired Redis handle of your app (see @softistx/alxia-redis), `signIn` a limit defined on it.
107
+ const fromRedis = {
108
+ consume: (key: string, cost: number) =>
109
+ handle.limits.signIn.consume({ ip: key }, cost),
110
+ };
111
+ ```
112
+
113
+ What to know when you pick a limit:
114
+
115
+ - **Partial charge.** Every unit the store accepted before a refusal stays
116
+ spent, and fields are charged in the order the document selects them:
117
+ earlier fields stay charged when a later one is refused.
118
+ - **Round trips.** `limitFromStore` calls the store once per unit, so one
119
+ selection count of N makes up to `limit + 1` calls (a refusal stops it).
120
+ With a large limit on a Redis store, use the cost-taking limit above.
121
+ - **What is counted.** Selections in the document as written: a list parent
122
+ costs 1 however long the list, `@skip` and `@include` are not evaluated,
123
+ selections that merge at execution still count each, and a field matches by
124
+ name on any type.
125
+ - **Batching.** Each operation of a batch is checked on its own. A refused
126
+ element is an error in an array answered 200, and there is no `Retry-After`
127
+ header: read `extensions.retryAfter`.
128
+ - **No address, no count.** `graphqlExecutor` has no `ip` in its server
129
+ context unless you give one, so a field is counted there only when `key` is
130
+ given.
131
+ - Subscriptions are not counted.
132
+
133
+ ## Limit depth and complexity
134
+
135
+ graxia refuses a document before it executes when it nests deeper than
136
+ `limits.depth` (12 by default), uses more than `limits.aliases` aliases (30),
137
+ `limits.directives` directives (50) or `limits.rootFields` root fields (20), or
138
+ costs more than `limits.cost.max` (5 000). All are on by default; size them
139
+ from your own clients' largest legitimate operation. Depth is one dimension:
140
+ aliases, list sizes and fragments multiply the work at a depth that is
141
+ allowed, so give every list argument a maximum in the schema.
142
+
143
+ ```ts
144
+ // file: src/depth.ts
145
+ // A document past a limit is refused at validation, before a resolver runs:
146
+ // a 400 whose error carries `extensions.limit` and `extensions.fix`.
147
+ export const operationLimits = { depth: 8, aliases: 10, rootFields: 10 };
148
+ ```
149
+
150
+ ## Introspection and suggestions off in production
151
+
152
+ Introspection hands anyone the whole schema, the fields you meant to keep
153
+ quiet included, and "Did you mean…" hints leak field names from a typo. Both
154
+ are on for development, where GraphiQL needs them, and off when
155
+ `NODE_ENV=production`. Say so in the app, so it holds whatever the
156
+ environment says: `introspection: false` and `suggestions: false` on
157
+ `graphql()`.
158
+
159
+ This hides the schema from a client that asks, not from one that guesses
160
+ field names: it is not authorisation.
161
+
162
+ ## Masked errors
163
+
164
+ graxia always masks errors: an `Error` a resolver throws reaches the client
165
+ as `Unexpected error.` with a correlation id (`extensions.reference`), and the
166
+ original goes to `onUnexpected` on the server. Leave it so. To tell the client
167
+ something, throw `exposedError(code, message)` from `@softistx/graxia`, or a
168
+ `GraphQLError` (shown as it is, so never put a secret in its message), with an
169
+ `extensions.code` the client can switch on. A status for the refusal is not
170
+ read from an `http.status` extension: graxia answers by its own rules (the
171
+ [layers of an auth error](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#auth-errors-in-three-layers)).
172
+
173
+ ```ts
174
+ // file: src/errors.ts
175
+ import { exposedError } from '@softistx/graxia';
176
+ import { GraphQLError } from 'graphql';
177
+
178
+ // What a client may read: a stable `code`, and a message meant for people.
179
+ export function invalid(message: string, field: string): GraphQLError {
180
+ return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT', field } });
181
+ }
182
+
183
+ export function notFound(what: string): Error {
184
+ return exposedError('NOT_FOUND', `No ${what}`);
185
+ }
186
+ ```
187
+
188
+ ## Cap what a request costs
189
+
190
+ graxia parses a document before any resolver guard runs, and a parsed
191
+ document stays in a cache. Both are bounded by default, by the document's
192
+ **tokens**: the words, names and punctuation the parser reads. Measured on
193
+ graphql 16 and 17, a parsed token costs between 178 and 509 bytes of heap
194
+ whatever its shape (4 000 aliases, one-character fields, nested lists,
195
+ directives), where the cost per character swings from 58 to 254. So the
196
+ count of tokens is the weight, and 512 bytes per token the upper estimate: a
197
+ document of 15 000 tokens parses to 7.7 MB at most (15 000 × 512 B); a
198
+ measured heavy document of about 12 000 tokens weighs about 6 MB.
199
+
200
+ The parse cache counts entries and age, not bytes: it keeps up to
201
+ `caches.parse.max` documents (1 024) for `ttlMs` (one hour). A few thousand
202
+ distinct large documents can therefore hold a lot of memory; lower `max`, or
203
+ send variables so documents repeat.
204
+
205
+ `limits.tokens` does not count comments, yet a parsed document keeps all of
206
+ them alive: a 750 KB body of `#` lines holds about 19.6 MB, which the body
207
+ limit, not the token limit, bounds.
208
+
209
+ - **`limits.tokens`, 15 000 by default** (Apollo Router's own limit; the
210
+ deprecated `maxTokens` still maps to it). The
211
+ introspection query is 163 tokens and a large screen query with its
212
+ fragments a few thousand, so a client written for a federated graph passes.
213
+ A longer one is refused before it runs, as any document the parser cannot
214
+ read is: `GRAPHQL_PARSE_FAILED`, `Syntax Error: Document contains more than
215
+ 15000 tokens. Parsing aborted.`, HTTP 400 under
216
+ `application/graphql-response+json` and 200 under `application/json`,
217
+ never logged. It applies to `POST`, `GET`, each operation of a batch and
218
+ each operation over WebSocket. `limits: { tokens: false }` turns it off.
219
+ - **`limits.nesting`, 1 000 by default** (the deprecated `maxNesting`). graphql-js
220
+ parses by recursion, so a document nested a few thousand levels deep
221
+ (`{ a { a { …`, `[[[…`) overflows the stack while it is still well under
222
+ the token limit. graxia scans the source for the nesting of `{`, `(` and `[`
223
+ first, linearly and ignoring strings, block strings and comments, and
224
+ refuses a deeper document as `GRAPHQL_PARSE_FAILED`, `Syntax Error:
225
+ Document is nested more than 1000 levels deep. Parsing aborted.`, with the
226
+ same status and no log as the token limit. A document that overflows the
227
+ stack anyway (nesting `false`, or a limit raised too far) is refused as
228
+ `Syntax Error: Document is nested too deeply to parse.` A real query nests a
229
+ dozen levels. It counts `{`, `(` and `[` together, arguments and lists
230
+ included, so it is not a selection-depth rule; use `limits.depth` for that
231
+ ([Limit depth and complexity](#limit-depth-and-complexity)).
232
+ - **`caches.parse`**, a least-recently-used cache per endpoint: `max`
233
+ documents (1 024) and `ttlMs` (one hour). `caches: false` keeps nothing.
234
+ A bad value of these options is not rejected where `graphql()` is declared
235
+ (only `bodyLimit` is); check them in review.
236
+
237
+ ```ts
238
+ graphql(app, {
239
+ schema,
240
+ limits: { tokens: 20_000 },
241
+ caches: { parse: { max: 256 } },
242
+ });
243
+ ```
244
+
245
+ ### The body
246
+
247
+ graxia reads the body of a `POST` as a stream and counts it, so a megabyte of
248
+ JSON never costs more than the limit. The limit is graxia's `limits.bodyBytes`:
249
+
250
+ - **`bodyLimit`, 1 MiB by default.** Give the option to `graphql()`, or
251
+ declare core's `bodyLimit(bytes)` before it: that limit is the one graxia
252
+ enforces, and the option wins over it. A query is a few kilobytes, so for an
253
+ API that takes no uploads, 100 KiB is generous. A mutation that takes a file
254
+ by `multipart` needs a larger limit, in the option. A plugin app mounted
255
+ under a prefix keeps the limit of its own scope; the outer app's
256
+ `bodyLimit()` does not reach it.
257
+ - **The 413.** A body past the limit, with a `Content-Length` or without one
258
+ (a chunked body), is `413` with `extensions.code: 'BODY_TOO_LARGE'`, in
259
+ graxia's JSON format whatever the app's `errors` option says, and with the
260
+ headers the plugins set. Match the code, never the message.
261
+ - **Other refusals.** A `Content-Type` that is not JSON is `415
262
+ UNSUPPORTED_MEDIA_TYPE` (a form or `application/graphql` body too, whatever
263
+ its size), a body that is not JSON is `400 BODY_NOT_JSON`, one that cannot be
264
+ read is `400 BODY_UNREADABLE`, and the parser's own error is never sent. The
265
+ whole list is graxia's [refusal codes](https://github.com/softistx/graxia/blob/develop/packages/core/docs/guide/http.md#refusal-codes);
266
+ the type of a code is `GraxiaErrorCode`, re-exported by `@softistx/alxia-graphql`.
267
+ Under `Accept: application/json` (the default) a 400 refusal is a `200`; `413`, `415`, `404`, `405` and `406` never change.
268
+ - **No double counting.** Core's own counter never runs on the endpoint's
269
+ `POST` (it would turn a chunked body past the limit into an unreadable
270
+ `400`), so the middlewares declared after `bodyLimit()` run for an oversized
271
+ body before graxia refuses it: declare the costly ones (a session lookup, a
272
+ database call) after the cheap guards, or let a gateway cap the size.
273
+
274
+ ```ts
275
+ graphql(app, {
276
+ schema,
277
+ limits: { tokens: 20_000 },
278
+ caches: { parse: { max: 512 } },
279
+ bodyLimit: 100 * 1024,
280
+ });
281
+ ```
282
+
283
+ ## CSRF for a cookie-authenticated API
284
+
285
+ A bearer token in a header cannot be sent by another site's form. A
286
+ **cookie** can: a page on another origin may make the browser `POST` the
287
+ cookie to `/graphql`. `SameSite=Lax` on the cookie is the first line (a
288
+ cross-site `POST` does not carry it); two more close the rest.
289
+
290
+ - Graxia's CSRF prevention (on by default, below) refuses a request without a
291
+ custom header: a browser cannot add one to a request across origins without
292
+ a CORS preflight, which `@softistx/alxia-cors` answers only for the origins you named.
293
+ - Require `application/json` on a `POST`, which an HTML form cannot send. A
294
+ form-encoded `POST` and a `GET` query are the two a form or a link can make,
295
+ so this is a middleware before the endpoint.
296
+
297
+ ```ts
298
+ // file: src/csrf.ts
299
+ import { defineMiddleware, HttpError } from '@softistx/alxia';
300
+
301
+ // A POST that is not JSON is refused with a 415 before graxia reads it.
302
+ export const jsonOnly = defineMiddleware(async ({ request }, next) => {
303
+ if (request.method === 'POST' && !request.headers.get('content-type')?.startsWith('application/json')) {
304
+ throw new HttpError(415, { error: 'unsupported_media_type' });
305
+ }
306
+ return next();
307
+ });
308
+ ```
309
+
310
+ `@softistx/alxia-graphql` runs on graxia, whose `csrf` option is on by default: a
311
+ `GET`, or a `POST` that is not JSON, needs one of the headers
312
+ `x-graphql-csrf`, `graphql-require-preflight`, `apollo-require-preflight` or
313
+ `x-apollo-operation-name`, and a WebSocket upgrade from another origin is
314
+ refused. Answer 403 `CSRF_HEADER_REQUIRED` otherwise. Tune it with
315
+ `csrf: { sameOrigin: true }` adds an origin check for a cookie session (off by default), and `csrf: false` turns it all off. Use it beside `SameSite` on
316
+ the cookie.
317
+
318
+ ## Persisted operations, briefly
319
+
320
+ A client that sends only the hash of an operation it registered at build
321
+ time cannot send any other: the strongest limit on what it can ask. Graxia's
322
+ `trustedDocuments` takes the manifest, and its `strict` mode refuses any
323
+ document that was not registered:
324
+
325
+ ```ts no-check
326
+ // file: src/persisted.ts
327
+ import { alxia } from '@softistx/alxia';
328
+ import { graphql } from '@softistx/alxia-graphql';
329
+
330
+ // Hash to document: from a file the build wrote, here a literal.
331
+ const manifest = { '5f1bb2a0c2a0': '{ notes { text } }' };
332
+
333
+ graphql(alxia(), { schema, trustedDocuments: { manifest, mode: 'strict' } });
334
+ ```
335
+
336
+ ## Together
337
+
338
+ `limits` and `caches` need no line here: their defaults apply. The
339
+ `bodyLimit()` below is the app's own and is kept; without it the `POST` takes
340
+ 1 MiB.
341
+
342
+ ```ts no-check
343
+ // file: src/production.ts
344
+ import { logger } from '@softistx/alxia-logger';
345
+ import { base } from './context';
346
+ import { jsonOnly } from './csrf';
347
+ import { operationLimits } from './depth';
348
+ import { limitTo } from './limits';
349
+ import { createLoaders } from './loaders';
350
+ import { schema } from './schema';
351
+ import { graphql } from '@softistx/alxia-graphql';
352
+
353
+ export const production = base.fork()
354
+ .use(logger())
355
+ .use(limitTo(120)) // the probes above it are not counted
356
+ .use(jsonOnly)
357
+ .bodyLimit(100 * 1024) // a body past 100 KiB is refused (a 413), for the routes below
358
+ .plugin((app) =>
359
+ graphql(app, {
360
+ schema,
361
+ context: () => ({ loaders: createLoaders() }),
362
+ limits: operationLimits,
363
+ introspection: false,
364
+ suggestions: false,
365
+ }),
366
+ );
367
+ ```
368
+
369
+ The recipe's spec runs each point against this app and a small schema, in
370
+ process: the 429 for a viewer and for an address (a batch of three counts
371
+ once), a document too deep, introspection refused, a masked `Error` beside a `GraphQLError` with its
372
+ extensions, the body limit, the CSRF header, the `415`, and a persisted
373
+ hash running while an arbitrary document is refused
374
+ ([the recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#7-harden-it-for-production)).
@@ -0,0 +1,171 @@
1
+ # Testing the endpoint
2
+
3
+ `graphqlClient` sends an operation to an app's GraphQL endpoint in process,
4
+ through `app.fetch`: no port, no server, and the whole chain in play (the
5
+ app's middlewares, its body limit, graxia's plugins). It is a helper for
6
+ specs, so it lives in its own subpath, `@softistx/alxia-graphql/testing`: the main
7
+ entry stays what an app ships, and a production bundle never carries it.
8
+
9
+ ```ts
10
+ import { expect, test } from 'bun:test';
11
+ import { graphqlClient } from '@softistx/alxia-graphql/testing';
12
+ import { app } from './app';
13
+
14
+ test('hello', async () => {
15
+ const { status, data, errors } = await graphqlClient(app).query(
16
+ 'query ($name: String!) { hello(name: $name) }',
17
+ { variables: { name: 'Ada' } },
18
+ );
19
+ expect(status).toBe(200);
20
+ expect(errors).toBeUndefined();
21
+ expect(data).toEqual({ hello: 'hello Ada' });
22
+ });
23
+ ```
24
+
25
+ ## What `app` can be
26
+
27
+ `graphqlClient` calls `app.fetch(request)`, so `app` is an alxia app or anything
28
+ with a `fetch(Request)` that answers a `Response`: a graxia instance (`createGraxia`), a
29
+ handler of your own, a stub.
30
+
31
+ ```ts
32
+ const client = graphqlClient({ fetch: (request) => graxia.fetch(request) });
33
+ ```
34
+
35
+ ## The result
36
+
37
+ `query` resolves to `{ status, data?, errors?, response }`:
38
+
39
+ | field | |
40
+ | --- | --- |
41
+ | `status` | the HTTP status: 200 for a GraphQL answer, errors included; 400 for a request graxia refuses under `application/graphql-response+json` (200 under `application/json`, the client's default), 401 or 403 from a guard or the CSRF check; a 413 over a body limit (`BODY_TOO_LARGE`) and a 415 are the same under either `Accept` |
42
+ | `data`, `errors` | the JSON body's own, each unset when the body has none |
43
+ | `response` | the `Response`, its body unread: `headers`, `ok` |
44
+
45
+ A GraphQL error is an entry of `errors`, never a rejection. A body that is
46
+ not JSON (a 404) leaves `data` and `errors` unset: read `status`. A graxia refusal such as a 413 is JSON: read `errors[0].extensions.code`.
47
+
48
+ ## Headers
49
+
50
+ `graphqlClient(app, { headers })` sends them with every query, which is
51
+ where a token goes; a call's `headers` are added to them, and replace one of
52
+ the same name:
53
+
54
+ ```ts
55
+ const ada = graphqlClient(app, { headers: { authorization: `Bearer ${token}` } });
56
+
57
+ expect((await ada.query('{ me { name } }')).data).toEqual({ me: { name: 'Ada' } });
58
+
59
+ const anonymous = await ada.query('{ me { name } }', { headers: { authorization: '' } });
60
+ ```
61
+
62
+ ## A custom path
63
+
64
+ `path` is the endpoint's, `/graphql` by default:
65
+
66
+ ```ts
67
+ const client = graphqlClient(app, { path: '/api/graphql' });
68
+ ```
69
+
70
+ ## Variables and operation names
71
+
72
+ ```ts
73
+ await client.query(document, { variables: { id: '1' }, operationName: 'GetNote' });
74
+ ```
75
+
76
+ `TData` and `TVars` are the result's and the variables' types, and default
77
+ to `unknown` and `Record<string, unknown>`; name them when the document is a
78
+ string: `client.query<{ me: { name: string } }>('{ me { name } }')`.
79
+
80
+ ## A typed document
81
+
82
+ A `TypedDocumentNode`, as GraphQL Code Generator's `typed-document-node`
83
+ plugin writes it (`@graphql-typed-document-node/core`), or `graphql`'s own
84
+ `TypedQueryDocumentNode`, is printed to a string, and gives `data` and
85
+ `variables` their types, with no extra dependency:
86
+
87
+ ```ts
88
+ import type { TypedQueryDocumentNode } from 'graphql';
89
+ import { parse } from 'graphql';
90
+
91
+ const Hello = parse('query Hello($name: String!) { hello(name: $name) }') as TypedQueryDocumentNode<
92
+ { hello: string },
93
+ { name: string }
94
+ >;
95
+
96
+ const { data } = await client.query(Hello, { variables: { name: 'Ada' } });
97
+ data?.hello; // string
98
+ // client.query(Hello, { variables: { name: 1 } }); // compile error
99
+ ```
100
+
101
+ ## GET
102
+
103
+ `method: 'GET'` puts the operation in the URL instead of a JSON body:
104
+ `query`, `operationName`, and `variables` and `extensions` as JSON. Set it
105
+ per call, or for every call with `graphqlClient(app, { method: 'GET' })`; a
106
+ call's own `method` wins.
107
+
108
+ ```ts
109
+ const { data } = await client.query('query ($name: String) { hello(name: $name) }', {
110
+ method: 'GET',
111
+ variables: { name: 'Ada' },
112
+ });
113
+ ```
114
+
115
+ A `GET` has no `Content-Type`.
116
+
117
+ ## Persisted operations
118
+
119
+ `persisted` is the hash of an operation the app registered. It is sent as
120
+ Apollo's `extensions.persistedQuery: { version: 1, sha256Hash }`, the shape
121
+ graxia's `trustedDocuments` reads. With no document, only the hash is
122
+ sent, so an app in `strict` mode can be tested; `TData` is yours to name,
123
+ since nothing types it:
124
+
125
+ ```ts
126
+ const result = await client.query<{ notes: { text: string }[] }>({
127
+ persisted: '5f1bb2a0c2a0',
128
+ variables: { first: 10 },
129
+ method: 'GET', // or the default POST
130
+ });
131
+ ```
132
+
133
+ With a document too, both are sent (Apollo's automatic persisted queries
134
+ register one that way, when `trustedDocuments.apq` is on). An unknown hash is
135
+ the server's own answer, not a client error: `errors[0].message` is
136
+ `PersistedQueryNotFound` (code `PERSISTED_QUERY_NOT_FOUND`), or
137
+ `PersistedQueryNotSupported` with `apq` off; a document sent to an app in
138
+ `strict` mode is `Only persisted documents are allowed.`
139
+ (`PERSISTED_QUERY_ONLY`).
140
+
141
+ An app that names an operation by an **id** in an extension of its own
142
+ (a custom `extractPersistedOperationId`) is sent that extension: `extensions`
143
+ is sent as given, and counts as a call with no document.
144
+
145
+ ```ts
146
+ await client.query({ extensions: { documentId: 'abc123' } });
147
+ ```
148
+
149
+ ## CSRF
150
+
151
+ A `GET` carries graxia's CSRF header, `x-graphql-csrf: 1`, by default, so a
152
+ spec passes on an app that keeps `csrf` on (graxia's default). A JSON `POST`
153
+ needs none (a browser preflights that content type) and is sent without.
154
+
155
+ An app that lists its own header (`csrf: { requireHeader: ['x-my-app'] }`)
156
+ names it in `csrfHeader`; `false` sends none, to test the refusal. A header
157
+ you set in `headers` or in a call is kept.
158
+
159
+ ```ts
160
+ graphqlClient(app); // GET sends x-graphql-csrf
161
+ graphqlClient(app, { csrfHeader: 'x-my-app' });
162
+ const refused = await graphqlClient(app, { csrfHeader: false }).query('{ me { name } }', { method: 'GET' });
163
+ expect(refused.status).toBe(403); // CSRF_HEADER_REQUIRED
164
+ ```
165
+
166
+ ## Not covered
167
+
168
+ A subscription over server-sent events or a socket, a form-encoded `POST`
169
+ and a batch are not sent by it; use `app.request` for those (the
170
+ [recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md#6-test-it-in-process)
171
+ reads a stream, and checks the 415 a form gets).