@alxia/graphql 0.2.0 → 0.3.1
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.
- package/README.md +29 -5
- package/dist/graphql.d.ts +9 -7
- package/dist/graphql.d.ts.map +1 -1
- package/dist/handler.d.ts +12 -3
- package/dist/handler.d.ts.map +1 -1
- package/dist/index.js +64 -15
- package/dist/index.js.map +6 -6
- package/docs/README.md +12 -2
- package/docs/guide/context.md +40 -0
- package/docs/guide/endpoint.md +48 -8
- package/docs/guide/ide.md +18 -9
- package/docs/guide/yoga.md +6 -5
- package/docs/roadmap.md +14 -3
- package/docs/troubleshooting.md +23 -3
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -75,7 +75,7 @@ graphql(app, {
|
|
|
75
75
|
schema,
|
|
76
76
|
plugins: [useDepthLimit({ maxDepth: 8 }), useResponseCache({ session: ({ request }) => ... })],
|
|
77
77
|
maskedErrors: true, // Yoga's default: an error's message never leaks
|
|
78
|
-
ide:
|
|
78
|
+
ide: Bun.env.NODE_ENV === 'development' && 'apollo-sandbox', // at runtime, never process.env: bun build inlines it
|
|
79
79
|
batching: true,
|
|
80
80
|
});
|
|
81
81
|
```
|
|
@@ -84,22 +84,45 @@ graphql(app, {
|
|
|
84
84
|
`async *subscribe` in a resolver, `Accept: text/event-stream` on the
|
|
85
85
|
request. `@alxia/compress` leaves an event stream alone by default.
|
|
86
86
|
- **An IDE** answers a `GET` from a browser at the endpoint, with a
|
|
87
|
-
`Content-Security-Policy` that lets it load —
|
|
88
|
-
|
|
87
|
+
`Content-Security-Policy` that lets it load — its pinned files on unpkg
|
|
88
|
+
alone, framed by no one — which `@alxia/secure-headers` keeps. By
|
|
89
|
+
default, GraphiQL in the serving app's dev alone (`NODE_ENV=development`,
|
|
90
|
+
or `alxia({ dev: true })`), none otherwise; `ide` chooses one everywhere:
|
|
89
91
|
|
|
90
92
|
```ts
|
|
93
|
+
graphql(app, { schema }); // GraphiQL in dev, nothing deployed
|
|
91
94
|
graphql(app, { schema, ide: 'apollo-sandbox', sandbox: { initialDocument: '{ me }' } });
|
|
92
|
-
graphql(app, { schema, ide: Bun.env.NODE_ENV === 'production' ? false : 'graphiql' });
|
|
93
95
|
```
|
|
94
96
|
|
|
95
97
|
| `ide` | |
|
|
96
98
|
| --- | --- |
|
|
97
|
-
|
|
|
99
|
+
| none (default) | Yoga's GraphiQL in dev (`isDev`), nothing otherwise |
|
|
100
|
+
| `'graphiql'` | Yoga's GraphiQL, everywhere; `graphiql` takes its options |
|
|
98
101
|
| `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded, pointed at the address the page was opened at, prefix included — `https` behind a proxy that terminates TLS ([IDE guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/ide.md#apollo-sandbox)). `sandbox` takes `title`, `initialDocument`, `initialHeaders`, `pollForSchemaUpdates`, `includeCookies` |
|
|
99
102
|
| `false` | none |
|
|
100
103
|
- **CORS** is `@alxia/cors`'s for the whole app: Yoga's own is off unless
|
|
101
104
|
`cors` is given.
|
|
102
105
|
|
|
106
|
+
## Errors, health and shutdown
|
|
107
|
+
|
|
108
|
+
A GraphQL error stays GraphQL's — an entry of `errors[]`, inside a 200 —
|
|
109
|
+
while `@alxia/core`'s `alxia({ errors: 'problem' })` makes the HTTP layer
|
|
110
|
+
around the endpoint answer RFC 9457 problems: a guard's 401, a 413, a
|
|
111
|
+
500. `health()` mounts beside it, and on `SIGTERM` the queries in flight
|
|
112
|
+
are answered and the subscriptions ended before the process exits:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { alxia, health } from '@alxia/core';
|
|
116
|
+
import { graphql } from '@alxia/graphql';
|
|
117
|
+
|
|
118
|
+
const app = alxia({ errors: 'problem' })
|
|
119
|
+
.plugin(health())
|
|
120
|
+
.plugin((app) => graphql(app, { schema }));
|
|
121
|
+
app.listen({ port: 4000 });
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
See [the endpoint guide](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/guide/endpoint.md#errors-health-and-shutdown).
|
|
125
|
+
|
|
103
126
|
## API
|
|
104
127
|
|
|
105
128
|
| export | |
|
|
@@ -115,3 +138,4 @@ graphql(app, {
|
|
|
115
138
|
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs): a page per area — mounting the endpoint, the typed context, Yoga's plugins and options, and GraphiQL and Apollo Sandbox.
|
|
116
139
|
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/troubleshooting.md): an error message, and what to do about it.
|
|
117
140
|
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/graphql/docs/roadmap.md): what is coming, and what is not planned.
|
|
141
|
+
- [Recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md): [A GraphQL API](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md), [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md), [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md), [Health checks and graceful shutdown](https://github.com/softistx/alxia/blob/develop/docs/recipes/health-and-shutdown.md), and more.
|
package/dist/graphql.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Alxia, type BaseContext, type Empty, type RoutePath } from '@alxia/core';
|
|
2
2
|
import type { GraphQLSchemaWithContext, YogaInitialContext, YogaServerOptions } from 'graphql-yoga';
|
|
3
3
|
import { type YogaContext } from './handler';
|
|
4
4
|
import type { SandboxOptions } from './sandbox';
|
|
5
5
|
/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */
|
|
6
6
|
type RouteOnly = 'params' | 'query' | 'headers' | 'cookies' | 'body' | 'reply' | 'redirect';
|
|
7
7
|
/**
|
|
8
|
-
* What alxia hands Yoga for each request: the context its
|
|
8
|
+
* What alxia hands Yoga for each request: the context its middlewares built —
|
|
9
9
|
* `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through
|
|
10
10
|
* which a resolver sets a cookie or a header on the response.
|
|
11
11
|
*/
|
|
@@ -27,7 +27,9 @@ export type GraphQLContext<App, UserContext = Empty> = App extends {
|
|
|
27
27
|
export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends YogaContext, Path extends RoutePath, SchemaCtx = unknown> extends Omit<YogaServerOptions<ServerCtx, UserCtx>, 'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'> {
|
|
28
28
|
/**
|
|
29
29
|
* What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,
|
|
30
|
-
* or nothing. GraphiQL
|
|
30
|
+
* or nothing. By default, GraphiQL in the serving app's dev alone
|
|
31
|
+
* (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing
|
|
32
|
+
* otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.
|
|
31
33
|
*/
|
|
32
34
|
readonly ide?: 'graphiql' | 'apollo-sandbox' | false;
|
|
33
35
|
/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */
|
|
@@ -37,7 +39,7 @@ export interface GraphQLOptions<ServerCtx extends YogaContext, UserCtx extends Y
|
|
|
37
39
|
/**
|
|
38
40
|
* The schema, from Yoga's `createSchema`, Pothos, or any tool that types
|
|
39
41
|
* its context. Its context must be one the app builds: a resolver that
|
|
40
|
-
* reads `user` behind no
|
|
42
|
+
* reads `user` behind no middleware that adds one is a compile error.
|
|
41
43
|
*/
|
|
42
44
|
readonly schema: GraphQLSchemaWithContext<SchemaCtx>;
|
|
43
45
|
/** Where the endpoint is, under the app's prefix. `/graphql` by default. */
|
|
@@ -58,8 +60,8 @@ type ProvidesContext<Provided, Required> = Provided extends Required ? unknown :
|
|
|
58
60
|
};
|
|
59
61
|
/**
|
|
60
62
|
* A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):
|
|
61
|
-
* `GET` and `POST` at `path`, behind every
|
|
62
|
-
* A guard before it guards it; what the
|
|
63
|
+
* `GET` and `POST` at `path`, behind every middleware given to `use` on `app`
|
|
64
|
+
* before it. A guard before it guards it; what the middlewares added is in each
|
|
63
65
|
* resolver's context, typed. Yoga's options pass through — `plugins`
|
|
64
66
|
* (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —
|
|
65
67
|
* and subscriptions are served over server-sent events.
|
|
@@ -70,6 +72,6 @@ type ProvidesContext<Provided, Required> = Provided extends Required ? unknown :
|
|
|
70
72
|
* .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));
|
|
71
73
|
* ```
|
|
72
74
|
*/
|
|
73
|
-
export declare function graphql<Ctx extends object, Prefix extends string,
|
|
75
|
+
export declare function graphql<Ctx extends object, Prefix extends string, SchemaCtx, UserCtx extends YogaContext = Empty, const Path extends RoutePath = '/graphql'>(app: Alxia<Ctx, Prefix>, options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> & ProvidesContext<YogaInitialContext & ServerContext<Ctx> & UserCtx, SchemaCtx>): Alxia<Ctx, Prefix>;
|
|
74
76
|
export {};
|
|
75
77
|
//# sourceMappingURL=graphql.d.ts.map
|
package/dist/graphql.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"graphql.d.ts","sourceRoot":"","sources":["../src/graphql.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,KAAK,EAEV,KAAK,SAAS,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACX,wBAAwB,EACxB,kBAAkB,EAClB,iBAAiB,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,WAAW,EAAe,MAAM,WAAW,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WA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,IAAI,CAAC,EAAE,iBAAiB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;CAC9D;AAED;;;;GAIG;AACH,KAAK,eAAe,CAAC,QAAQ,EAAE,QAAQ,IAAI,QAAQ,SAAS,QAAQ,GACjE,OAAO,GACP;IACA,QAAQ,CAAC,MAAM,EAAE,yEAAyE,OAAO,CAChG,MAAM,QAAQ,EACd,MAAM,QAAQ,CACd,GACA,MAAM,EAAE,CAAC;CACV,CAAC;AAEJ;;;;;;;;;;;;;GAaG;AACH,wBAAgB,OAAO,CACtB,GAAG,SAAS,MAAM,EAClB,MAAM,SAAS,MAAM,EACrB,SAAS,EACT,OAAO,SAAS,WAAW,GAAG,KAAK,EACnC,KAAK,CAAC,IAAI,SAAS,SAAS,GAAG,UAAU,EAEzC,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,EACvB,OAAO,EAAE,cAAc,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,GACpE,eAAe,CACd,kBAAkB,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,OAAO,EACjD,SAAS,CACT,GACA,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CA+BpB"}
|
package/dist/handler.d.ts
CHANGED
|
@@ -2,10 +2,19 @@
|
|
|
2
2
|
* The endpoint behind `graphql()`: one Yoga per path it is served at, and
|
|
3
3
|
* the route handler that hands each request to it.
|
|
4
4
|
*/
|
|
5
|
-
import type
|
|
5
|
+
import { type BaseContext, type StatusCode } from '@alxia/core';
|
|
6
6
|
import { type YogaServerInstance, type YogaServerOptions } from 'graphql-yoga';
|
|
7
7
|
import { type SandboxOptions } from './sandbox';
|
|
8
8
|
export type YogaContext = Record<string, any>;
|
|
9
|
+
/**
|
|
10
|
+
* What GraphiQL's page may load: its scripts, styles and Monaco's
|
|
11
|
+
* workers from the exact version of `@graphql-yoga/graphiql` the page
|
|
12
|
+
* names, fetched and run as blobs; queries to this server alone; framed
|
|
13
|
+
* by no one. A page that names none (a `renderGraphiQL` of the app's own)
|
|
14
|
+
* gets this server alone. `@alxia/secure-headers` keeps a policy a
|
|
15
|
+
* response already has.
|
|
16
|
+
*/
|
|
17
|
+
export declare function graphiqlPolicy(html: string): string;
|
|
9
18
|
/**
|
|
10
19
|
* The Yoga serving `endpoint`, created on first use. One per path: a plugin
|
|
11
20
|
* mounted under a prefix serves the same routes at a longer path, and
|
|
@@ -15,10 +24,10 @@ export declare function yogaServers<UserCtx extends YogaContext>(options: Omit<Y
|
|
|
15
24
|
/**
|
|
16
25
|
* The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to
|
|
17
26
|
* a browser when `sandbox` is not `false`, else the request to Yoga, with
|
|
18
|
-
* the route's context — the
|
|
27
|
+
* the route's context — the middlewares' work, minus what a resolver has no use
|
|
19
28
|
* for — as Yoga's server context.
|
|
20
29
|
*/
|
|
21
30
|
export declare function graphqlHandler<UserCtx extends YogaContext>(yogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>, sandbox: SandboxOptions | false): (ctx: Record<string, unknown> & BaseContext & {
|
|
22
31
|
readonly route: string;
|
|
23
|
-
}) => Promise<import("@alxia/core").Reply<
|
|
32
|
+
}) => Promise<import("@alxia/core").Reply<StatusCode, string> | import("@alxia/core").Reply<StatusCode, ReadableStream<Uint8Array<ArrayBufferLike>>>>;
|
|
24
33
|
//# sourceMappingURL=handler.d.ts.map
|
package/dist/handler.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,UAAU,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAiC,KAAK,cAAc,EAAE,MAAM,WAAW,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAM9C;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAanD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,SAAS,WAAW,EACtD,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,EAAE,iBAAiB,CAAC,GACvE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,CAahE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,SAAS,WAAW,EACzD,MAAM,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,kBAAkB,CAAC,WAAW,EAAE,OAAO,CAAC,EACtE,OAAO,EAAE,cAAc,GAAG,KAAK,IAK9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,qJA2CxE"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
// src/graphql.ts
|
|
2
|
+
import {
|
|
3
|
+
isDev
|
|
4
|
+
} from "@alxia/core";
|
|
5
|
+
|
|
1
6
|
// src/handler.ts
|
|
7
|
+
import { shutdownSignal } from "@alxia/core";
|
|
2
8
|
import {
|
|
3
9
|
createYoga
|
|
4
10
|
} from "graphql-yoga";
|
|
@@ -54,15 +60,21 @@ function script(value) {
|
|
|
54
60
|
}
|
|
55
61
|
|
|
56
62
|
// src/handler.ts
|
|
57
|
-
var
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
"
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
var GRAPHIQL_FILES = /https:\/\/unpkg\.com\/@graphql-yoga\/graphiql@[\w.-]+\//;
|
|
64
|
+
function graphiqlPolicy(html) {
|
|
65
|
+
const files = html.match(GRAPHIQL_FILES)?.[0] ?? "";
|
|
66
|
+
const from = files === "" ? "" : ` ${files}`;
|
|
67
|
+
return [
|
|
68
|
+
"default-src 'self'",
|
|
69
|
+
`script-src 'self' 'unsafe-inline'${from}`,
|
|
70
|
+
`style-src 'self' 'unsafe-inline'${from}`,
|
|
71
|
+
"img-src 'self' data: https:",
|
|
72
|
+
`font-src 'self' data:${from}`,
|
|
73
|
+
"worker-src 'self' blob:",
|
|
74
|
+
`connect-src 'self'${from}`,
|
|
75
|
+
"frame-ancestors 'none'"
|
|
76
|
+
].join("; ");
|
|
77
|
+
}
|
|
66
78
|
function yogaServers(options) {
|
|
67
79
|
const servers = new Map;
|
|
68
80
|
return (endpoint) => {
|
|
@@ -78,7 +90,7 @@ function yogaServers(options) {
|
|
|
78
90
|
};
|
|
79
91
|
}
|
|
80
92
|
function graphqlHandler(yogaAt, sandbox) {
|
|
81
|
-
return async (ctx)
|
|
93
|
+
return async function graphql(ctx) {
|
|
82
94
|
const {
|
|
83
95
|
params: _params,
|
|
84
96
|
query: _query,
|
|
@@ -100,28 +112,65 @@ function graphqlHandler(yogaAt, sandbox) {
|
|
|
100
112
|
const response = await yogaAt(ctx.route).fetch(ctx.request, server);
|
|
101
113
|
const headers = new Headers(response.headers);
|
|
102
114
|
if (headers.get("content-type")?.startsWith("text/html") && !headers.has("content-security-policy")) {
|
|
103
|
-
|
|
115
|
+
const html = await response.text();
|
|
116
|
+
headers.set("content-security-policy", graphiqlPolicy(html));
|
|
117
|
+
return reply(response.status, html, { headers });
|
|
104
118
|
}
|
|
105
|
-
|
|
119
|
+
const body = endedOnShutdown(response, shutdownSignal(ctx));
|
|
120
|
+
return reply(response.status, body ?? undefined, {
|
|
106
121
|
headers
|
|
107
122
|
});
|
|
108
123
|
};
|
|
109
124
|
}
|
|
125
|
+
function endedOnShutdown(response, signal) {
|
|
126
|
+
const body = response.body;
|
|
127
|
+
const type = response.headers.get("content-type") ?? "";
|
|
128
|
+
if (body === null || !/text\/event-stream|multipart\/mixed/.test(type)) {
|
|
129
|
+
return body;
|
|
130
|
+
}
|
|
131
|
+
const reader = body.getReader();
|
|
132
|
+
return new ReadableStream({
|
|
133
|
+
start(controller) {
|
|
134
|
+
const end = () => {
|
|
135
|
+
reader.cancel();
|
|
136
|
+
try {
|
|
137
|
+
controller.close();
|
|
138
|
+
} catch {}
|
|
139
|
+
};
|
|
140
|
+
if (signal.aborted)
|
|
141
|
+
end();
|
|
142
|
+
else
|
|
143
|
+
signal.addEventListener("abort", end, { once: true });
|
|
144
|
+
},
|
|
145
|
+
async pull(controller) {
|
|
146
|
+
const { value, done } = await reader.read();
|
|
147
|
+
if (done) {
|
|
148
|
+
try {
|
|
149
|
+
controller.close();
|
|
150
|
+
} catch {}
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
controller.enqueue(value);
|
|
154
|
+
},
|
|
155
|
+
cancel: (reason) => reader.cancel(reason)
|
|
156
|
+
});
|
|
157
|
+
}
|
|
110
158
|
|
|
111
159
|
// src/graphql.ts
|
|
112
160
|
function graphql(app, options) {
|
|
113
161
|
const {
|
|
114
162
|
path = "/graphql",
|
|
115
163
|
cors = false,
|
|
116
|
-
ide
|
|
164
|
+
ide,
|
|
117
165
|
graphiql,
|
|
118
166
|
sandbox,
|
|
119
167
|
...yogaOptions
|
|
120
168
|
} = options;
|
|
169
|
+
const page = graphiql ?? true;
|
|
121
170
|
const yogaAt = yogaServers({
|
|
122
171
|
...yogaOptions,
|
|
123
172
|
cors,
|
|
124
|
-
graphiql: ide === "graphiql" ?
|
|
173
|
+
graphiql: ide === undefined ? (_request, context) => isDev(context) && page : ide === "graphiql" ? page : false
|
|
125
174
|
});
|
|
126
175
|
const handler = graphqlHandler(yogaAt, ide === "apollo-sandbox" ? sandbox ?? {} : false);
|
|
127
176
|
const route = app;
|
|
@@ -135,5 +184,5 @@ export {
|
|
|
135
184
|
renderSandbox
|
|
136
185
|
};
|
|
137
186
|
|
|
138
|
-
//# debugId=
|
|
187
|
+
//# debugId=36F374D7B3E2E7EE64756E2164756E21
|
|
139
188
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
3
|
+
"sources": ["../src/graphql.ts", "../src/handler.ts", "../src/sandbox.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"
|
|
6
|
-
"/**\n *
|
|
7
|
-
"
|
|
5
|
+
"import {\n\ttype Alxia,\n\ttype BaseContext,\n\ttype Empty,\n\tisDev,\n\ttype RoutePath,\n} from '@alxia/core';\nimport type {\n\tGraphQLSchemaWithContext,\n\tYogaInitialContext,\n\tYogaServerOptions,\n} from 'graphql-yoga';\nimport { graphqlHandler, type YogaContext, yogaServers } from './handler';\nimport type { SandboxOptions } from './sandbox';\n\n/** The parts of a route's context Yoga owns, or that mean nothing to a resolver. */\ntype RouteOnly =\n\t| 'params'\n\t| 'query'\n\t| 'headers'\n\t| 'cookies'\n\t| 'body'\n\t| 'reply'\n\t| 'redirect';\n\n/**\n * What alxia hands Yoga for each request: the context its middlewares built —\n * `user`, `db`, `log`… — with `request`, `url`, `ip` and `set`, through\n * which a resolver sets a cookie or a header on the response.\n */\nexport type ServerContext<Ctx> = Omit<BaseContext & Ctx, RouteOnly>;\n\n/**\n * What a resolver reads as its context: Yoga's own, the app's, and what\n * the `context` option adds. Type a schema with it:\n *\n * ```ts\n * const base = alxia().use(bearer({ jwt }));\n * const schema = createSchema<GraphQLContext<typeof base>>({ ... });\n * ```\n */\nexport type GraphQLContext<App, UserContext = Empty> = App extends {\n\treadonly '~context': infer Ctx;\n}\n\t? YogaInitialContext & ServerContext<Ctx> & UserContext\n\t: // Not `never`: a schema typed with `never` would let every resolver\n\t\t// read anything until `graphql()` refused it.\n\t\t{\n\t\t\treadonly '~error': 'GraphQLContext needs the type of an app: GraphQLContext<typeof app>';\n\t\t};\n\nexport interface GraphQLOptions<\n\tServerCtx extends YogaContext,\n\tUserCtx extends YogaContext,\n\tPath extends RoutePath,\n\tSchemaCtx = unknown,\n> extends Omit<\n\t\tYogaServerOptions<ServerCtx, UserCtx>,\n\t\t'graphqlEndpoint' | 'cors' | 'schema' | 'graphiql'\n\t> {\n\t/**\n\t * What a browser gets at the endpoint: Yoga's GraphiQL, Apollo Sandbox,\n\t * or nothing. By default, GraphiQL in the serving app's dev alone\n\t * (`isDev`: `alxia({ dev })`, else `NODE_ENV=development`), nothing\n\t * otherwise; `graphiql` or `apollo-sandbox` serves one everywhere.\n\t */\n\treadonly ide?: 'graphiql' | 'apollo-sandbox' | false;\n\t/** GraphiQL's options, Yoga's own, when `ide` is `graphiql`. */\n\treadonly graphiql?: Exclude<\n\t\tYogaServerOptions<ServerCtx, UserCtx>['graphiql'],\n\t\tboolean\n\t>;\n\t/** Apollo Sandbox's options, when `ide` is `apollo-sandbox`. */\n\treadonly sandbox?: SandboxOptions;\n\t/**\n\t * The schema, from Yoga's `createSchema`, Pothos, or any tool that types\n\t * its context. Its context must be one the app builds: a resolver that\n\t * reads `user` behind no middleware that adds one is a compile error.\n\t */\n\treadonly schema: GraphQLSchemaWithContext<SchemaCtx>;\n\t/** Where the endpoint is, under the app's prefix. `/graphql` by default. */\n\treadonly path?: Path;\n\t/**\n\t * Yoga's own CORS. Off by default: `@alxia/cors` answers for the whole\n\t * app, this endpoint included.\n\t */\n\treadonly cors?: YogaServerOptions<ServerCtx, UserCtx>['cors'];\n}\n\n/**\n * The check Yoga's types leave out: the context the app builds must hold\n * what the schema's resolvers read. A mistake comes back as a `schema`\n * whose type is the message.\n */\ntype ProvidesContext<Provided, Required> = Provided extends Required\n\t? unknown\n\t: {\n\t\t\treadonly schema: `the schema's resolvers read a context the app does not build: missing ${Exclude<\n\t\t\t\tkeyof Required,\n\t\t\t\tkeyof Provided\n\t\t\t> &\n\t\t\t\tstring}`;\n\t\t};\n\n/**\n * A GraphQL endpoint on `app`, served by [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server):\n * `GET` and `POST` at `path`, behind every middleware given to `use` on `app`\n * before it. A guard before it guards it; what the middlewares added is in each\n * resolver's context, typed. Yoga's options pass through — `plugins`\n * (Envelop's and Yoga's), `graphiql`, `maskedErrors`, `batching`… —\n * and subscriptions are served over server-sent events.\n *\n * ```ts\n * const app = alxia()\n * .use(bearer({ jwt }))\n * .plugin((app) => graphql(app, { schema, plugins: [useDepthLimit()] }));\n * ```\n */\nexport function graphql<\n\tCtx extends object,\n\tPrefix extends string,\n\tSchemaCtx,\n\tUserCtx extends YogaContext = Empty,\n\tconst Path extends RoutePath = '/graphql',\n>(\n\tapp: Alxia<Ctx, Prefix>,\n\toptions: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx> &\n\t\tProvidesContext<\n\t\t\tYogaInitialContext & ServerContext<Ctx> & UserCtx,\n\t\t\tSchemaCtx\n\t\t>,\n): Alxia<Ctx, Prefix> {\n\tconst {\n\t\tpath = '/graphql' as Path,\n\t\tcors = false,\n\t\tide,\n\t\tgraphiql,\n\t\tsandbox,\n\t\t...yogaOptions\n\t} = options;\n\tconst page = graphiql ?? true;\n\tconst yogaAt = yogaServers<UserCtx>({\n\t\t...(yogaOptions as YogaServerOptions<YogaContext, UserCtx>),\n\t\tcors,\n\t\tgraphiql: (ide === undefined\n\t\t\t? (_request: Request, context: object) => isDev(context) && page\n\t\t\t: ide === 'graphiql'\n\t\t\t\t? page\n\t\t\t\t: false) as YogaServerOptions<YogaContext, UserCtx>['graphiql'],\n\t});\n\tconst handler = graphqlHandler(\n\t\tyogaAt,\n\t\tide === 'apollo-sandbox' ? (sandbox ?? {}) : false,\n\t);\n\n\tconst route = app as unknown as {\n\t\tget(path: string, handler: unknown): unknown;\n\t\tpost(path: string, handler: unknown): unknown;\n\t};\n\troute.get(path, handler);\n\troute.post(path, handler);\n\treturn app as never;\n}\n",
|
|
6
|
+
"/**\n * The endpoint behind `graphql()`: one Yoga per path it is served at, and\n * the route handler that hands each request to it.\n */\nimport { type BaseContext, type StatusCode, shutdownSignal } from '@alxia/core';\nimport {\n\tcreateYoga,\n\ttype YogaServerInstance,\n\ttype YogaServerOptions,\n} from 'graphql-yoga';\nimport { renderSandbox, SANDBOX_POLICY, type SandboxOptions } from './sandbox';\n\nexport type YogaContext = Record<string, any>;\n\n/** Where Yoga's GraphiQL page loads its files from: one pinned version on unpkg. */\nconst GRAPHIQL_FILES =\n\t/https:\\/\\/unpkg\\.com\\/@graphql-yoga\\/graphiql@[\\w.-]+\\//;\n\n/**\n * What GraphiQL's page may load: its scripts, styles and Monaco's\n * workers from the exact version of `@graphql-yoga/graphiql` the page\n * names, fetched and run as blobs; queries to this server alone; framed\n * by no one. A page that names none (a `renderGraphiQL` of the app's own)\n * gets this server alone. `@alxia/secure-headers` keeps a policy a\n * response already has.\n */\nexport function graphiqlPolicy(html: string): string {\n\tconst files = html.match(GRAPHIQL_FILES)?.[0] ?? '';\n\tconst from = files === '' ? '' : ` ${files}`;\n\treturn [\n\t\t\"default-src 'self'\",\n\t\t`script-src 'self' 'unsafe-inline'${from}`,\n\t\t`style-src 'self' 'unsafe-inline'${from}`,\n\t\t\"img-src 'self' data: https:\",\n\t\t`font-src 'self' data:${from}`,\n\t\t\"worker-src 'self' blob:\",\n\t\t`connect-src 'self'${from}`,\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * The Yoga serving `endpoint`, created on first use. One per path: a plugin\n * mounted under a prefix serves the same routes at a longer path, and\n * GraphiQL must ask that one.\n */\nexport function yogaServers<UserCtx extends YogaContext>(\n\toptions: Omit<YogaServerOptions<YogaContext, UserCtx>, 'graphqlEndpoint'>,\n): (endpoint: string) => YogaServerInstance<YogaContext, UserCtx> {\n\tconst servers = new Map<string, YogaServerInstance<YogaContext, UserCtx>>();\n\treturn (endpoint) => {\n\t\tlet yoga = servers.get(endpoint);\n\t\tif (yoga === undefined) {\n\t\t\tyoga = createYoga<YogaContext, UserCtx>({\n\t\t\t\t...options,\n\t\t\t\tgraphqlEndpoint: endpoint,\n\t\t\t});\n\t\t\tservers.set(endpoint, yoga);\n\t\t}\n\t\treturn yoga;\n\t};\n}\n\n/**\n * The handler of the endpoint's `GET` and `POST`: Apollo Sandbox's page to\n * a browser when `sandbox` is not `false`, else the request to Yoga, with\n * the route's context — the middlewares' work, minus what a resolver has no use\n * for — as Yoga's server context.\n */\nexport function graphqlHandler<UserCtx extends YogaContext>(\n\tyogaAt: (endpoint: string) => YogaServerInstance<YogaContext, UserCtx>,\n\tsandbox: SandboxOptions | false,\n) {\n\t// A handler's context: its route is the one it was declared at. Named\n\t// `graphql`, the name the route table `listen` prints in dev shows.\n\treturn async function graphql(\n\t\tctx: Record<string, unknown> & BaseContext & { readonly route: string },\n\t) {\n\t\tconst {\n\t\t\tparams: _params,\n\t\t\tquery: _query,\n\t\t\theaders: _headers,\n\t\t\tcookies: _cookies,\n\t\t\tbody: _body,\n\t\t\treply,\n\t\t\tredirect: _redirect,\n\t\t\t...server\n\t\t} = ctx;\n\t\tif (\n\t\t\tsandbox !== false &&\n\t\t\tctx.request.method === 'GET' &&\n\t\t\tctx.request.headers.get('accept')?.includes('text/html') &&\n\t\t\t!ctx.url.searchParams.has('query')\n\t\t) {\n\t\t\t// A path: the page resolves it against its own address, so behind\n\t\t\t// a TLS proxy the Sandbox asks over https, as the browser did.\n\t\t\treturn reply(200, renderSandbox(ctx.route, sandbox), {\n\t\t\t\theaders: {\n\t\t\t\t\t'content-type': 'text/html;charset=utf-8',\n\t\t\t\t\t'content-security-policy': SANDBOX_POLICY,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst response = await yogaAt(ctx.route).fetch(ctx.request, server);\n\t\tconst headers = new Headers(response.headers);\n\t\tif (\n\t\t\theaders.get('content-type')?.startsWith('text/html') &&\n\t\t\t!headers.has('content-security-policy')\n\t\t) {\n\t\t\t// GraphiQL's page: its policy names the files it loads.\n\t\t\tconst html = await response.text();\n\t\t\theaders.set('content-security-policy', graphiqlPolicy(html));\n\t\t\treturn reply(response.status as StatusCode, html, { headers });\n\t\t}\n\t\tconst body = endedOnShutdown(response, shutdownSignal(ctx));\n\t\treturn reply(response.status as StatusCode, body ?? undefined, {\n\t\t\theaders,\n\t\t});\n\t};\n}\n\n/**\n * A subscription's or an incremental delivery's body, which streams until\n * its reader stops: ended when the app starts shutting down — Yoga's\n * stream cancelled, as when the client leaves, and the client reading its\n * end — so the drain does not wait for it. Any other body finishes within\n * the drain as it is.\n */\nfunction endedOnShutdown(\n\tresponse: Response,\n\tsignal: AbortSignal,\n): ReadableStream<Uint8Array> | null {\n\tconst body = response.body;\n\tconst type = response.headers.get('content-type') ?? '';\n\tif (body === null || !/text\\/event-stream|multipart\\/mixed/.test(type)) {\n\t\treturn body;\n\t}\n\tconst reader = body.getReader();\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst end = () => {\n\t\t\t\tvoid reader.cancel();\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the stream had ended.\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal.aborted) end();\n\t\t\telse signal.addEventListener('abort', end, { once: true });\n\t\t},\n\t\tasync pull(controller) {\n\t\t\tconst { value, done } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Closed already: the shutdown ended it.\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontroller.enqueue(value);\n\t\t},\n\t\tcancel: (reason) => reader.cancel(reason),\n\t});\n}\n",
|
|
7
|
+
"/**\n * [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox),\n * embedded: the page a browser gets at the endpoint when the IDE is\n * `apollo-sandbox`. `@nxgt/shared-graphql`'s `renderSandbox`, kept twice: the\n * Sandbox asks the address the page was opened at, as there since\n * nxgt-core#171, but here the page resolves the path itself, so a TLS proxy\n * in front changes nothing.\n */\n\nexport interface SandboxOptions {\n\t/** The page's title. `Sandbox Explorer` by default. */\n\treadonly title?: string;\n\t/** The operation the Sandbox opens with. */\n\treadonly initialDocument?: string;\n\t/** Headers every operation sends, shown and editable in the Sandbox. */\n\treadonly initialHeaders?: Readonly<Record<string, string>>;\n\t/** Whether the Sandbox polls the schema as it changes. On by default. */\n\treadonly pollForSchemaUpdates?: boolean;\n\t/** Whether operations send the browser's cookies: a session cookie. On by default. */\n\treadonly includeCookies?: boolean;\n}\n\n/** What the page loads: the Sandbox's script, its frame, and operations to this server. */\nexport const SANDBOX_POLICY = [\n\t\"default-src 'self'\",\n\t\"script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com\",\n\t\"style-src 'self' 'unsafe-inline'\",\n\t'frame-src https://sandbox.embed.apollographql.com',\n\t\"img-src 'self' data: https:\",\n\t\"connect-src 'self'\",\n].join('; ');\n\n/**\n * The page, its endpoint `endpoint`: a URL, or a path the page resolves\n * against its own address. Every value is escaped into its JavaScript and\n * HTML.\n */\nexport function renderSandbox(\n\tendpoint: string,\n\toptions: SandboxOptions = {},\n): string {\n\tconst config = {\n\t\ttarget: '#sandbox',\n\t\tinitialEndpoint: endpoint,\n\t\tinitialState: {\n\t\t\tincludeCookies: options.includeCookies ?? true,\n\t\t\tpollForSchemaUpdates: options.pollForSchemaUpdates ?? true,\n\t\t\t...(options.initialDocument === undefined\n\t\t\t\t? {}\n\t\t\t\t: { document: options.initialDocument }),\n\t\t\t...(options.initialHeaders === undefined\n\t\t\t\t? {}\n\t\t\t\t: { headers: options.initialHeaders }),\n\t\t},\n\t\thideCookieToggle: false,\n\t\tendpointIsEditable: false,\n\t};\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>${html(options.title ?? 'Sandbox Explorer')}</title>\n<style>html, body { margin: 0; height: 100%; } #sandbox { position: absolute; inset: 0; }</style>\n</head>\n<body>\n<div id=\"sandbox\"></div>\n<script src=\"https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js\"></script>\n<script>\n{\nconst config = ${script(config)};\nconfig.initialEndpoint = new URL(config.initialEndpoint, location.href).href;\nnew window.EmbeddedSandbox(config);\n}\n</script>\n</body>\n</html>`;\n}\n\nfunction html(text: string): string {\n\treturn text.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n}\n\n/** JSON that cannot close the `<script>` it is written in. */\nfunction script(value: unknown): string {\n\treturn JSON.stringify(value)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": ";AAAA;AAAA;AAAA;;;ACIA;AACA;AAAA;AAAA;;;ACkBO,IAAM,iBAAiB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,EAAE,KAAK,IAAI;AAOJ,SAAS,aAAa,CAC5B,UACA,UAA0B,CAAC,GAClB;AAAA,EACT,MAAM,SAAS;AAAA,IACd,QAAQ;AAAA,IACR,iBAAiB;AAAA,IACjB,cAAc;AAAA,MACb,gBAAgB,QAAQ,kBAAkB;AAAA,MAC1C,sBAAsB,QAAQ,wBAAwB;AAAA,SAClD,QAAQ,oBAAoB,YAC7B,CAAC,IACD,EAAE,UAAU,QAAQ,gBAAgB;AAAA,SACnC,QAAQ,mBAAmB,YAC5B,CAAC,I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
"debugId": "36F374D7B3E2E7EE64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
package/docs/README.md
CHANGED
|
@@ -8,9 +8,19 @@ a realistic example for each.
|
|
|
8
8
|
|
|
9
9
|
| Page | Read it when |
|
|
10
10
|
| --- | --- |
|
|
11
|
-
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, or testing it without a server |
|
|
11
|
+
| [Mounting the endpoint](guide/endpoint.md) | adding GraphQL to an app, choosing its path under a prefix, putting it behind a guard, reading what it answers, telling GraphQL errors from the problem details of the HTTP layer around it, adding `health()` probes and draining it on `SIGTERM`, or testing it without a server |
|
|
12
12
|
| [The typed context](guide/context.md) | typing a schema with the app's context, reading `user` or a database handle in a resolver, setting a cookie, adding per-request loaders, or reading the `missing …` compile error |
|
|
13
13
|
| [Yoga's plugins and options](guide/yoga.md) | adding Yoga or Envelop plugins, exposing or masking errors, batching, serving subscriptions, or calling the endpoint from another origin |
|
|
14
|
-
| [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or
|
|
14
|
+
| [GraphiQL and Apollo Sandbox](guide/ide.md) | choosing the IDE a browser gets, configuring it, keeping it working under a strict `Content-Security-Policy`, or serving it outside dev with `ide: 'graphiql'` |
|
|
15
15
|
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message |
|
|
16
16
|
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
|
17
|
+
|
|
18
|
+
## Recipes
|
|
19
|
+
|
|
20
|
+
A task that crosses packages, in [the repository's recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md), each with a complete example:
|
|
21
|
+
|
|
22
|
+
- [A GraphQL API](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md): typed resolvers, a viewer, subscriptions, GraphiQL, auth errors and the drain
|
|
23
|
+
- [Authenticate requests](https://github.com/softistx/alxia/blob/develop/docs/recipes/authentication.md): a bearer token or a cookie session, a role check, the user typed in every handler
|
|
24
|
+
- [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md): `app.request`, a middleware alone, the typed client, sockets, Redis
|
|
25
|
+
- [Health checks and graceful shutdown](https://github.com/softistx/alxia/blob/develop/docs/recipes/health-and-shutdown.md): probes, the drain, Docker and Kubernetes
|
|
26
|
+
- [Deploy with Docker](https://github.com/softistx/alxia/blob/develop/docs/recipes/deploying.md): the build stage, the final image, `NODE_ENV=production`
|
package/docs/guide/context.md
CHANGED
|
@@ -217,6 +217,46 @@ Prefer a `derive` on the app for what every route needs — the user, a
|
|
|
217
217
|
database handle — and the `context` option for what only resolvers do, such
|
|
218
218
|
as per-request data loaders.
|
|
219
219
|
|
|
220
|
+
## Batching with DataLoader (N+1)
|
|
221
|
+
|
|
222
|
+
A field that loads a record for each parent, `Note.author` over a list of
|
|
223
|
+
notes, runs a query per parent: 50 notes, 51 queries. A
|
|
224
|
+
[DataLoader](https://github.com/graphql/dataloader) collects the `load` calls
|
|
225
|
+
of one tick and calls your batch function once. Build the loaders in the
|
|
226
|
+
`context` option, so each request has its own, and type them through
|
|
227
|
+
`GraphQLContext`'s second argument, so every resolver reads `loaders` typed:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
import DataLoader from 'dataloader';
|
|
231
|
+
|
|
232
|
+
// `findUsers` is your batch query: one result per id, in the order of the ids.
|
|
233
|
+
|
|
234
|
+
const createLoaders = () => ({
|
|
235
|
+
user: new DataLoader(async (ids: readonly string[]) => findUsers(ids)), // one query for all ids
|
|
236
|
+
});
|
|
237
|
+
type Loaders = ReturnType<typeof createLoaders>;
|
|
238
|
+
type Context = GraphQLContext<typeof base, { loaders: Loaders }>;
|
|
239
|
+
|
|
240
|
+
const schema = createSchema<Context>({
|
|
241
|
+
typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Note { author: User! } type Query { notes: [Note!]! }`,
|
|
242
|
+
resolvers: { Note: { author: (note: { authorId: string }, _, { loaders }) => loaders.user.load(note.authorId) } },
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
const app = base.plugin((app) =>
|
|
246
|
+
graphql(app, { schema, context: () => ({ loaders: createLoaders() }) }),
|
|
247
|
+
);
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**The loaders must be per request.** A DataLoader caches every key it loads.
|
|
251
|
+
Created once, at module level or with `decorate`, its cache outlives the
|
|
252
|
+
request: it keeps serving a record after an update, grows for the life of the
|
|
253
|
+
process, and a loader that reads with the viewer's permissions hands one
|
|
254
|
+
user's data to the next. Per request, the cache lives and dies with one
|
|
255
|
+
response, and the same user loaded twice in it is one lookup.
|
|
256
|
+
|
|
257
|
+
The [GraphQL recipe](https://github.com/softistx/alxia/blob/develop/docs/recipes/graphql-api.md)
|
|
258
|
+
builds this step by step, with a spec that counts the calls to the store: five notes, one batch.
|
|
259
|
+
|
|
220
260
|
## See also
|
|
221
261
|
|
|
222
262
|
- [Mounting the endpoint](endpoint.md): which middlewares run before it.
|
package/docs/guide/endpoint.md
CHANGED
|
@@ -28,10 +28,10 @@ curl localhost:3000/graphql -H 'content-type: application/json' -d '{"query":"{
|
|
|
28
28
|
## `graphql`
|
|
29
29
|
|
|
30
30
|
```ts
|
|
31
|
-
function graphql<Ctx, Prefix,
|
|
32
|
-
app: Alxia<Ctx, Prefix
|
|
31
|
+
function graphql<Ctx, Prefix, SchemaCtx, UserCtx = Empty, const Path = '/graphql'>(
|
|
32
|
+
app: Alxia<Ctx, Prefix>,
|
|
33
33
|
options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx>,
|
|
34
|
-
): Alxia<Ctx, Prefix
|
|
34
|
+
): Alxia<Ctx, Prefix>;
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
`graphql` declares a `GET` and a `POST` route at `path` on `app`, and returns
|
|
@@ -87,20 +87,24 @@ const app = alxia()
|
|
|
87
87
|
|
|
88
88
|
## Behind the app's middlewares
|
|
89
89
|
|
|
90
|
-
The endpoint is a route like any other: every middleware
|
|
91
|
-
it runs first, and one that replies ends the request there. A
|
|
92
|
-
it guards it
|
|
90
|
+
The endpoint is a route like any other: every middleware given to `use`
|
|
91
|
+
**before** it runs first, and one that replies ends the request there. A
|
|
92
|
+
guard before it guards it — a plain `(ctx, next)` function, what it passes
|
|
93
|
+
`next` typed into each resolver's context:
|
|
93
94
|
|
|
94
95
|
```ts
|
|
95
96
|
const app = alxia()
|
|
96
|
-
.
|
|
97
|
+
.use(({ request, reply }, next) =>
|
|
97
98
|
request.headers.get('authorization') === `Bearer ${Bun.env['API_TOKEN']}`
|
|
98
|
-
? { viewer: 'service' }
|
|
99
|
+
? next({ viewer: 'service' })
|
|
99
100
|
: reply(401, { error: 'unauthorized' as const }),
|
|
100
101
|
)
|
|
101
102
|
.plugin((app) => graphql(app, { schema })); // 401 without the token
|
|
102
103
|
```
|
|
103
104
|
|
|
105
|
+
`@alxia/jwt`'s `bearer()` is that guard for a JWT: `.use(bearer({ jwt }))`
|
|
106
|
+
([The typed context](context.md#with-a-token-alxiajwt)).
|
|
107
|
+
|
|
104
108
|
A middleware declared **after** `app.plugin` does not run for the endpoint: it
|
|
105
109
|
answers without it. Give the observers (`@alxia/logger`, `@alxia/cors`,
|
|
106
110
|
`@alxia/secure-headers`, `@alxia/compress`) to `use` first, so they wrap the
|
|
@@ -151,6 +155,42 @@ POST {} → 200 {"errors":[{"message":"Must provid
|
|
|
151
155
|
Both methods answer a body to read as GraphQL, whatever its status, and
|
|
152
156
|
the replies of the middlewares before them — a guard's `401`, say.
|
|
153
157
|
|
|
158
|
+
## Errors, health and shutdown
|
|
159
|
+
|
|
160
|
+
**GraphQL errors stay GraphQL's.** A resolver that throws, a query that
|
|
161
|
+
does not validate, is an entry of `errors[]` in Yoga's answer — inside a
|
|
162
|
+
`200`, as the GraphQL over HTTP specification has it — whatever
|
|
163
|
+
`@alxia/core`'s `errors` option says. `alxia({ errors: 'problem' })`
|
|
164
|
+
applies to the HTTP layer around the endpoint: `@alxia/jwt`'s 401 before
|
|
165
|
+
it, a body past its `bodyLimit` (413), a middleware's 500, a `PUT` at its
|
|
166
|
+
path (405) — each an `application/problem+json` problem
|
|
167
|
+
([core's errors guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/errors.md#graphql)).
|
|
168
|
+
|
|
169
|
+
```text
|
|
170
|
+
POST {"query":"{ boom }"} → 200 {"data":{"boom":null},"errors":[{"message":"Unexpected error.", …}]}
|
|
171
|
+
POST without a token → 401 application/problem+json {"type":"about:blank","title":"Unauthorized", …}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
**Probes and the drain.** `@alxia/core`'s `health()` mounts beside the
|
|
175
|
+
endpoint, and `listen`'s graceful shutdown covers it: on `SIGTERM` a
|
|
176
|
+
query or a mutation in flight is answered, and a subscription over
|
|
177
|
+
server-sent events ends — its stream cancelled as when the client leaves,
|
|
178
|
+
the client reading the end and reconnecting elsewhere — so the drain does
|
|
179
|
+
not wait for it until `shutdownTimeout`.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { alxia, health } from '@alxia/core';
|
|
183
|
+
import { bearer } from '@alxia/jwt';
|
|
184
|
+
import { graphql } from '@alxia/graphql';
|
|
185
|
+
|
|
186
|
+
const app = alxia({ errors: 'problem' })
|
|
187
|
+
.plugin(health({ checks: { db: () => sql`select 1` } }))
|
|
188
|
+
.use(bearer({ jwt }))
|
|
189
|
+
.plugin((app) => graphql(app, { schema }));
|
|
190
|
+
|
|
191
|
+
app.listen({ port: 4000 }); // SIGTERM: /ready 503, queries answered, subscriptions ended, exit 0
|
|
192
|
+
```
|
|
193
|
+
|
|
154
194
|
## Testing it
|
|
155
195
|
|
|
156
196
|
The endpoint runs in process through `app.request` or `app.fetch`, like
|
package/docs/guide/ide.md
CHANGED
|
@@ -18,7 +18,7 @@ const schema = createSchema({
|
|
|
18
18
|
const app = alxia().plugin((app) =>
|
|
19
19
|
graphql(app, {
|
|
20
20
|
schema,
|
|
21
|
-
ide: Bun.env['NODE_ENV'] === '
|
|
21
|
+
ide: Bun.env['NODE_ENV'] === 'development' && 'apollo-sandbox', // read at runtime
|
|
22
22
|
sandbox: { title: 'Hello API', initialDocument: '{ hello }' },
|
|
23
23
|
}),
|
|
24
24
|
);
|
|
@@ -29,7 +29,8 @@ const app = alxia().plugin((app) =>
|
|
|
29
29
|
|
|
30
30
|
| `ide` | A browser's `GET` at the endpoint gets | Options |
|
|
31
31
|
| --- | --- | --- |
|
|
32
|
-
|
|
|
32
|
+
| not given (default) | Yoga's GraphiQL in the serving app's dev — `alxia({ dev })`, else `NODE_ENV=development` — and no page elsewhere | `graphiql` |
|
|
33
|
+
| `'graphiql'` | Yoga's GraphiQL, in every mode | `graphiql` |
|
|
33
34
|
| `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded | `sandbox` |
|
|
34
35
|
| `false` | no page: the request is answered as a GraphQL request | — |
|
|
35
36
|
|
|
@@ -45,12 +46,13 @@ body](../troubleshooting.md#406-with-an-empty-body) instead.
|
|
|
45
46
|
Both IDEs run the schema's introspection and any operation against the
|
|
46
47
|
endpoint, behind the same middlewares as every other request: a guard before
|
|
47
48
|
the endpoint guards the page too, and a browser without a token gets the
|
|
48
|
-
guard's reply.
|
|
49
|
-
it.
|
|
49
|
+
guard's reply. By default the IDE is off outside dev; give `ide:
|
|
50
|
+
'graphiql'` only where you mean to publish it. Before 0.5, GraphiQL was
|
|
51
|
+
on in every mode.
|
|
50
52
|
|
|
51
53
|
## GraphiQL
|
|
52
54
|
|
|
53
|
-
The default. `graphiql` takes Yoga's `GraphiQLOptions` — not `true` or
|
|
55
|
+
The default, in dev. `graphiql` takes Yoga's `GraphiQLOptions` — not `true` or
|
|
54
56
|
`false`, which `ide` decides:
|
|
55
57
|
|
|
56
58
|
```ts
|
|
@@ -68,13 +70,20 @@ Its other options — `subscriptionsProtocol`, `credentials`,
|
|
|
68
70
|
`additionalHeaders`… — are listed in
|
|
69
71
|
[Yoga's GraphiQL documentation](https://the-guild.dev/graphql/yoga-server/docs/features/graphiql).
|
|
70
72
|
|
|
71
|
-
The page loads GraphiQL from `unpkg.com
|
|
72
|
-
`
|
|
73
|
+
The page loads GraphiQL from one pinned folder on `unpkg.com`,
|
|
74
|
+
`https://unpkg.com/@graphql-yoga/graphiql@<version>/`, the version the
|
|
75
|
+
installed Yoga names. Yoga's response has no `Content-Security-Policy`, so
|
|
76
|
+
the package adds one that lets that folder alone load — its scripts,
|
|
77
|
+
styles and fonts, and the Monaco workers the page fetches — and no one
|
|
78
|
+
frame the page:
|
|
73
79
|
|
|
74
80
|
```text
|
|
75
|
-
default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com
|
|
81
|
+
default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com/@graphql-yoga/graphiql@<version>/; style-src 'self' 'unsafe-inline' https://unpkg.com/@graphql-yoga/graphiql@<version>/; img-src 'self' data: https:; font-src 'self' data: https://unpkg.com/@graphql-yoga/graphiql@<version>/; worker-src 'self' blob:; connect-src 'self' https://unpkg.com/@graphql-yoga/graphiql@<version>/; frame-ancestors 'none'
|
|
76
82
|
```
|
|
77
83
|
|
|
84
|
+
A page of your own (`renderGraphiQL`) that names no such folder gets
|
|
85
|
+
`'self'` alone.
|
|
86
|
+
|
|
78
87
|
## Apollo Sandbox
|
|
79
88
|
|
|
80
89
|
`ide: 'apollo-sandbox'` serves a page embedding Apollo Sandbox, pointed at
|
|
@@ -150,7 +159,7 @@ const app = alxia()
|
|
|
150
159
|
|
|
151
160
|
## `renderSandbox`
|
|
152
161
|
|
|
153
|
-
```ts
|
|
162
|
+
```ts no-check
|
|
154
163
|
function renderSandbox(endpoint: string, options?: SandboxOptions): string;
|
|
155
164
|
const SANDBOX_POLICY: string;
|
|
156
165
|
```
|
package/docs/guide/yoga.md
CHANGED
|
@@ -84,9 +84,9 @@ const slowOperations: Plugin = {
|
|
|
84
84
|
graphql(app, { schema, plugins: [slowOperations] });
|
|
85
85
|
```
|
|
86
86
|
|
|
87
|
-
Yoga's plugins run inside the route, after the app's
|
|
88
|
-
sees only requests the
|
|
89
|
-
added.
|
|
87
|
+
Yoga's plugins run inside the route, after the app's middlewares: a plugin
|
|
88
|
+
sees only requests the middlewares let through, and its context holds what
|
|
89
|
+
they added.
|
|
90
90
|
|
|
91
91
|
## Errors
|
|
92
92
|
|
|
@@ -122,8 +122,9 @@ const resolvers = {
|
|
|
122
122
|
```
|
|
123
123
|
|
|
124
124
|
`maskedErrors: false` sends every message as it is: for development only.
|
|
125
|
-
A resolver's error is Yoga's to answer; it
|
|
126
|
-
|
|
125
|
+
A resolver's error is Yoga's to answer; it never reaches a try/catch
|
|
126
|
+
middleware before the endpoint, which sees only what fails around it — a
|
|
127
|
+
middleware that throws, say.
|
|
127
128
|
|
|
128
129
|
## Batching
|
|
129
130
|
|
package/docs/roadmap.md
CHANGED
|
@@ -7,7 +7,18 @@ number on it. Every release, with each change it made, is in
|
|
|
7
7
|
|
|
8
8
|
## Now
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
- **GraphiQL in dev alone, under a pinned policy.** Without `ide`, a
|
|
11
|
+
browser gets GraphiQL only while the serving app is in dev
|
|
12
|
+
(`NODE_ENV=development`, or `alxia({ dev: true })`); `ide: 'graphiql'`
|
|
13
|
+
serves it everywhere. Its `Content-Security-Policy` allows the one
|
|
14
|
+
pinned `@graphql-yoga/graphiql` folder it loads from, the Monaco workers
|
|
15
|
+
included, and no frame ([IDE guide](guide/ide.md)).
|
|
16
|
+
- **Subscriptions drained on shutdown.** When the app starts shutting
|
|
17
|
+
down — `SIGTERM`, `SIGINT`, `stop()` — a subscription over server-sent
|
|
18
|
+
events ends, so `@alxia/core`'s drain answers the queries in flight and
|
|
19
|
+
exits without waiting for it; `health()` probes mount beside the
|
|
20
|
+
endpoint, and GraphQL errors stay in `errors[]` under core's problem
|
|
21
|
+
details ([endpoint guide](guide/endpoint.md#errors-health-and-shutdown)).
|
|
11
22
|
|
|
12
23
|
## Next
|
|
13
24
|
|
|
@@ -24,11 +35,11 @@ Nothing scheduled yet.
|
|
|
24
35
|
- **GraphQL Yoga as a route.** `graphql(app, options)` serves a schema at
|
|
25
36
|
`GET` and `POST` `/graphql`, or any `path`, under the app's prefix and
|
|
26
37
|
the prefix of every app it is mounted into. The endpoint runs behind the
|
|
27
|
-
app's
|
|
38
|
+
app's middlewares like any route: a guard given to `use` before it guards it, and its
|
|
28
39
|
reply is part of the endpoint's type.
|
|
29
40
|
- **The app's context in every resolver, typed and checked.**
|
|
30
41
|
`GraphQLContext<typeof app>` types a schema with Yoga's context and
|
|
31
|
-
everything the app's
|
|
42
|
+
everything the app's middlewares add — a user, a database handle — plus `set`,
|
|
32
43
|
through which a resolver sets a header or a cookie. A schema whose
|
|
33
44
|
resolvers read what the app does not build is a compile error naming the
|
|
34
45
|
missing field, and `GraphQLContext` of anything but an app is a message
|
package/docs/troubleshooting.md
CHANGED
|
@@ -39,6 +39,7 @@ symptom.
|
|
|
39
39
|
- [A WebSocket client cannot connect: `Expected 101 status code`](#a-websocket-client-cannot-connect-expected-101-status-code)
|
|
40
40
|
- [The IDE page is blank](#the-ide-page-is-blank)
|
|
41
41
|
- [GraphiQL is served in production](#graphiql-is-served-in-production)
|
|
42
|
+
- [GraphiQL does not open in development, or in a test](#graphiql-does-not-open-in-development-or-in-a-test)
|
|
42
43
|
|
|
43
44
|
## Install
|
|
44
45
|
|
|
@@ -434,10 +435,29 @@ app.use(defaultPolicy); // before the endpoint, so it wraps it
|
|
|
434
435
|
|
|
435
436
|
**When:** a browser opening the production endpoint gets GraphiQL.
|
|
436
437
|
|
|
437
|
-
**Why:** `ide
|
|
438
|
+
**Why:** the app gives `ide: 'graphiql'`, which serves it in every mode, or
|
|
439
|
+
the serving app is in dev there (`NODE_ENV=development`, or
|
|
440
|
+
`alxia({ dev: true })`). Without `ide`, GraphiQL follows the dev switch
|
|
441
|
+
since 0.5; before, it was on everywhere.
|
|
438
442
|
|
|
439
|
-
**Fix:**
|
|
443
|
+
**Fix:** leave `ide` out, and keep `NODE_ENV=development` out of the
|
|
444
|
+
deployed environment, or turn it off:
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
graphql(app, { schema, ide: false });
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### GraphiQL does not open in development, or in a test
|
|
451
|
+
|
|
452
|
+
**When:** a browser's `GET` at the endpoint gets a JSON result, or
|
|
453
|
+
`Must provide query string.`, where GraphiQL used to open.
|
|
454
|
+
|
|
455
|
+
**Why:** without `ide`, GraphiQL is served in the serving app's dev alone,
|
|
456
|
+
on only under `NODE_ENV=development`; `bun test` sets `NODE_ENV=test`.
|
|
457
|
+
|
|
458
|
+
**Fix:** run the `dev` script with `NODE_ENV=development`, or give the IDE
|
|
459
|
+
explicitly where it must open:
|
|
440
460
|
|
|
441
461
|
```ts
|
|
442
|
-
graphql(app, { schema, ide:
|
|
462
|
+
graphql(app, { schema, ide: 'graphiql' });
|
|
443
463
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alxia/graphql",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "GraphQL for alxia with GraphQL Yoga: its plugins, subscriptions over SSE and GraphiQL, behind the app's hooks, its resolvers reading the app's typed context",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -41,13 +41,14 @@
|
|
|
41
41
|
]
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@alxia/core": "^0.
|
|
44
|
+
"@alxia/core": "^0.6.0",
|
|
45
45
|
"@types/bun": "^1.4.2",
|
|
46
|
+
"dataloader": "^2.2.3",
|
|
46
47
|
"graphql": "^16.11.0",
|
|
47
48
|
"graphql-yoga": "^5.16.0"
|
|
48
49
|
},
|
|
49
50
|
"peerDependencies": {
|
|
50
|
-
"@alxia/core": "^0.
|
|
51
|
+
"@alxia/core": "^0.6.0",
|
|
51
52
|
"graphql": "^16.11.0 || ^17.0.0",
|
|
52
53
|
"graphql-yoga": "^5.16.0",
|
|
53
54
|
"typescript": "^6.0.3 || ^7.0.0"
|