@alxia/graphql 0.1.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.
- package/LICENSE +21 -0
- package/README.md +117 -0
- package/dist/graphql.d.ts +78 -0
- package/dist/graphql.d.ts.map +1 -0
- package/dist/handler.d.ts +22 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +139 -0
- package/dist/index.js.map +12 -0
- package/dist/sandbox.d.ts +29 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/docs/README.md +16 -0
- package/docs/guide/context.md +224 -0
- package/docs/guide/endpoint.md +184 -0
- package/docs/guide/ide.md +186 -0
- package/docs/guide/yoga.md +226 -0
- package/docs/roadmap.md +45 -0
- package/docs/troubleshooting.md +396 -0
- package/package.json +55 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# The typed context
|
|
2
|
+
|
|
3
|
+
This page covers what a resolver reads as its context — Yoga'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 '@alxia/core';
|
|
9
|
+
import { graphql, type GraphQLContext } from '@alxia/graphql';
|
|
10
|
+
import { createSchema } from 'graphql-yoga';
|
|
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.use((app) => graphql(app, { schema }));
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Declare the hooks 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
|
+
YogaInitialContext & ServerContext<ContextOf<App>> & 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>"; } & YogaInitialContext'.
|
|
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---yogainitialcontext)).
|
|
62
|
+
|
|
63
|
+
A resolver's context holds:
|
|
64
|
+
|
|
65
|
+
| From | Fields |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| Yoga (`YogaInitialContext`) | `request`, and `params`: the GraphQL request's `query`, `variables`, `operationName`, `extensions` |
|
|
68
|
+
| the app's hooks | everything `decorate` and `derive` added before the endpoint, and what plugins such as `@alxia/jwt`'s `bearer` add (`user`) |
|
|
69
|
+
| the route (`BaseContext`) | `url`, `ip`, `server`, `route`, `pathParams`, `error`, and `set` |
|
|
70
|
+
| the `context` option | what it returns, as `UserContext` ([below](#the-context-option)) |
|
|
71
|
+
|
|
72
|
+
What a route handler reads but a resolver does not: `query`, `headers`,
|
|
73
|
+
`cookies` and `body` are the GraphQL request's, read through `request` and
|
|
74
|
+
`params`; `reply` and `redirect` answer a route, not a field. `params` is
|
|
75
|
+
Yoga's, not the route's path parameters. A resolver that reads one is a
|
|
76
|
+
compile error:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
error TS2339: Property 'query' does not exist on type 'YogaInitialContext & ServerContext<…> & Empty'.
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Read a header or a cookie from `request`:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
const locale = (_: unknown, __: unknown, { request }: GraphQLContext<typeof base>) =>
|
|
86
|
+
request.headers.get('accept-language') ?? 'en';
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Setting a header or a cookie
|
|
90
|
+
|
|
91
|
+
`set` is the route's: what a resolver sets on it is on the response, beside
|
|
92
|
+
Yoga's own headers.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const schema = createSchema<GraphQLContext<typeof base>>({
|
|
96
|
+
typeDefs: /* GraphQL */ `type Query { ok: Boolean } type Mutation { login(name: String!): Boolean! }`,
|
|
97
|
+
resolvers: {
|
|
98
|
+
Mutation: {
|
|
99
|
+
login: (_, { name }: { name: string }, { set }) => {
|
|
100
|
+
set.cookies.set('session', name, { httpOnly: true, sameSite: 'lax' });
|
|
101
|
+
set.headers.set('cache-control', 'no-store');
|
|
102
|
+
return true;
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`set.cookies` is a `Bun.CookieMap`: each `set` or `delete` is a
|
|
110
|
+
`Set-Cookie` header. `set.headers` is a `Headers`.
|
|
111
|
+
|
|
112
|
+
## The compile check
|
|
113
|
+
|
|
114
|
+
Yoga's types alone accept any schema. `graphql` also checks that the
|
|
115
|
+
context the app builds holds what the schema's resolvers read. A schema
|
|
116
|
+
typed with a context the app does not build is refused, and the error names
|
|
117
|
+
the missing field:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const app = alxia().use((app) => graphql(app, { schema })); // no hook derives `viewer` or `users`
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
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")'.
|
|
125
|
+
…
|
|
126
|
+
Type 'GraphQLSchemaWithContext<…>' is not assignable to type '"the schema's resolvers read a context the app does not build: missing viewer"'.
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
With `exactOptionalPropertyTypes` on, the code is `TS2375`; the message
|
|
130
|
+
ends the same way. The fix is to mount the endpoint on the
|
|
131
|
+
app the schema was typed from, after its hooks:
|
|
132
|
+
[Troubleshooting](../troubleshooting.md#the-schemas-resolvers-read-a-context-the-app-does-not-build-missing-).
|
|
133
|
+
|
|
134
|
+
An untyped schema — `createSchema({ … })` with no type argument — passes
|
|
135
|
+
on any app, but its resolvers see Yoga's context only: reading `viewer`
|
|
136
|
+
there is `Property 'viewer' does not exist`. Type the schema to read the
|
|
137
|
+
app's context.
|
|
138
|
+
|
|
139
|
+
## With a token: `@alxia/jwt`
|
|
140
|
+
|
|
141
|
+
A guard plugin is a hook like any other. With `@alxia/jwt`'s `bearer`, the
|
|
142
|
+
endpoint requires a token and `user` is the token's claims, typed by the
|
|
143
|
+
schema you give it:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import { alxia } from '@alxia/core';
|
|
147
|
+
import { graphql, type GraphQLContext } from '@alxia/graphql';
|
|
148
|
+
import { bearer, createJwt } from '@alxia/jwt';
|
|
149
|
+
import { createSchema } from 'graphql-yoga';
|
|
150
|
+
import { z } from 'zod';
|
|
151
|
+
|
|
152
|
+
const jwt = createJwt({ secret: Bun.env['JWT_SECRET']! });
|
|
153
|
+
const Claims = z.object({ sub: z.string(), role: z.enum(['admin', 'user']) });
|
|
154
|
+
|
|
155
|
+
const base = alxia().use(bearer({ jwt, schema: Claims })); // 401 without a valid token
|
|
156
|
+
|
|
157
|
+
const schema = createSchema<GraphQLContext<typeof base>>({
|
|
158
|
+
typeDefs: /* GraphQL */ `type Query { me: String!, isAdmin: Boolean! }`,
|
|
159
|
+
resolvers: {
|
|
160
|
+
Query: {
|
|
161
|
+
me: (_, __, { user }) => user.sub, // user: { sub: string; role: 'admin' | 'user' }
|
|
162
|
+
isAdmin: (_, __, { user }) => user.role === 'admin',
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const app = base.use((app) => graphql(app, { schema }));
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The guard's `401` and its body are `@alxia/jwt`'s, described in its
|
|
171
|
+
[bearer guard guide](https://github.com/softistx/alxia/blob/develop/packages/jwt/docs/guide/bearer-guard.md).
|
|
172
|
+
|
|
173
|
+
## The `context` option
|
|
174
|
+
|
|
175
|
+
Yoga's `context` option adds to the context per request. Its argument is
|
|
176
|
+
the context so far — Yoga's and the app's — and what it returns is merged
|
|
177
|
+
in. Give its type to `GraphQLContext` as the second argument:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
type Loaders = { loaders: { user: (id: string) => Promise<User | null> } };
|
|
181
|
+
|
|
182
|
+
const schema = createSchema<GraphQLContext<typeof base, Loaders>>({
|
|
183
|
+
typeDefs: /* GraphQL */ `type User { id: ID!, name: String! } type Query { user(id: ID!): User }`,
|
|
184
|
+
resolvers: {
|
|
185
|
+
Query: { user: (_, { id }: { id: string }, { loaders }) => loaders.user(id) },
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const app = base.use((app) =>
|
|
190
|
+
graphql(app, {
|
|
191
|
+
schema,
|
|
192
|
+
// annotate the argument: see below
|
|
193
|
+
context: ({ users }: GraphQLContext<typeof base>) => ({
|
|
194
|
+
loaders: { user: async (id: string) => users.get(id) ?? null },
|
|
195
|
+
}),
|
|
196
|
+
}),
|
|
197
|
+
);
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Without the `context` option, the same schema is refused: the error ends in
|
|
201
|
+
`missing loaders`.
|
|
202
|
+
|
|
203
|
+
**Annotate the argument when the function reads it.** TypeScript infers
|
|
204
|
+
`UserContext` from what the function returns only when the function does
|
|
205
|
+
not depend on its parameter's contextual type. `({ users }) => …`
|
|
206
|
+
unannotated leaves `UserContext` as `Empty`, and the schema is refused
|
|
207
|
+
with `missing loaders` although the function returns them. A function that
|
|
208
|
+
takes no argument, or annotates it, is inferred:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
context: () => ({ loaders: createLoaders() }), // inferred
|
|
212
|
+
context: ({ users }: GraphQLContext<typeof base>) => ({ loaders: …(users) }), // inferred
|
|
213
|
+
context: ({ users }) => ({ loaders: …(users) }), // `missing loaders`
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Prefer a `derive` on the app for what every route needs — the user, a
|
|
217
|
+
database handle — and the `context` option for what only resolvers do, such
|
|
218
|
+
as per-request data loaders.
|
|
219
|
+
|
|
220
|
+
## See also
|
|
221
|
+
|
|
222
|
+
- [Mounting the endpoint](endpoint.md): which hooks run before it.
|
|
223
|
+
- [Hooks](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/hooks.md),
|
|
224
|
+
in `@alxia/core`'s guide: `decorate` and `derive`.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Mounting the endpoint
|
|
2
|
+
|
|
3
|
+
This page covers `graphql(app, options)`: where the endpoint is served, what
|
|
4
|
+
it answers, which hooks run before it, and how to test it.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { alxia } from '@alxia/core';
|
|
8
|
+
import { graphql } from '@alxia/graphql';
|
|
9
|
+
import { createSchema } from 'graphql-yoga';
|
|
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
|
+
.use((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, Routes, Prefix, Shortcuts, SchemaCtx, UserCtx = Empty, const Path = '/graphql'>(
|
|
32
|
+
app: Alxia<Ctx, Routes, Prefix, Shortcuts>,
|
|
33
|
+
options: GraphQLOptions<ServerContext<Ctx>, UserCtx, Path, SchemaCtx>,
|
|
34
|
+
): Alxia<Ctx, Routes & GraphQLRoutes<JoinPath<Prefix, Path>, Shortcuts>, Prefix, Shortcuts>;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`graphql` declares a `GET` and a `POST` route at `path` on `app`, and returns
|
|
38
|
+
`app` with those two routes in its type. Hand it to `use` 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.use((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 Yoga's `createSchema` 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'` | What a browser gets at the endpoint: see [GraphiQL and Apollo Sandbox](ide.md). |
|
|
55
|
+
| `graphiql` | Yoga's `GraphiQLOptions` | Yoga's | GraphiQL's options, when `ide` is `'graphiql'`. |
|
|
56
|
+
| `sandbox` | `SandboxOptions` | — | Apollo Sandbox's options, when `ide` is `'apollo-sandbox'`. |
|
|
57
|
+
| `cors` | Yoga's `cors` | `false` | Yoga's own CORS. Off: use `@alxia/cors` for the whole app instead ([Yoga's plugins and options](yoga.md#cors)). |
|
|
58
|
+
| every other Yoga option | | Yoga's | `plugins`, `context`, `maskedErrors`, `batching`, `logging`… passed to `createYoga` as they are: see [Yoga's plugins and options](yoga.md). |
|
|
59
|
+
|
|
60
|
+
`graphqlEndpoint` is not an option: `path` sets it.
|
|
61
|
+
|
|
62
|
+
## Where it is served
|
|
63
|
+
|
|
64
|
+
`path` is joined to the app's prefix, and to the prefix of every app it is
|
|
65
|
+
mounted into, in the routes' type as at runtime:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { alxia, type RoutesOf } from '@alxia/core';
|
|
69
|
+
|
|
70
|
+
const api = alxia({ prefix: '/api' })
|
|
71
|
+
.use((app) => graphql(app, { schema, path: '/gql' })); // /api/gql
|
|
72
|
+
|
|
73
|
+
const root = alxia({ prefix: '/v1' }).use(api); // /v1/api/gql
|
|
74
|
+
|
|
75
|
+
type Paths = keyof RoutesOf<typeof root>; // '/v1/api/gql'
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Two endpoints on one app need two paths: declaring the default path twice
|
|
79
|
+
throws `GET /graphql is declared twice` when the app is built. Give each its
|
|
80
|
+
own path:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const app = alxia()
|
|
84
|
+
.use((app) => graphql(app, { schema }))
|
|
85
|
+
.use((app) => graphql(app, { schema: admin, path: '/admin/graphql' }));
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Behind the app's hooks
|
|
89
|
+
|
|
90
|
+
The endpoint is a route like any other: every route hook declared **before**
|
|
91
|
+
it runs first, and one that replies ends the request there. A guard before
|
|
92
|
+
it guards it:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const app = alxia()
|
|
96
|
+
.derive(({ request, reply }) =>
|
|
97
|
+
request.headers.get('authorization') === `Bearer ${Bun.env['API_TOKEN']}`
|
|
98
|
+
? { viewer: 'service' }
|
|
99
|
+
: reply(401, { error: 'unauthorized' as const }),
|
|
100
|
+
)
|
|
101
|
+
.use((app) => graphql(app, { schema })); // 401 without the token
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A hook declared **after** `use` does not run for it: the endpoint answers
|
|
105
|
+
without it. The order is core's, explained in
|
|
106
|
+
[Hooks](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/hooks.md#route-hooks-and-global-hooks).
|
|
107
|
+
Global hooks — `onRequest`, `onResponse`, `around`, and the plugins built on
|
|
108
|
+
them, such as `@alxia/cors` or `@alxia/secure-headers` — apply wherever they
|
|
109
|
+
are declared.
|
|
110
|
+
|
|
111
|
+
What the hooks added is in each resolver's context: that is the next page,
|
|
112
|
+
[The typed context](context.md).
|
|
113
|
+
|
|
114
|
+
## What it answers
|
|
115
|
+
|
|
116
|
+
Yoga answers the request; the package passes its status, headers and body
|
|
117
|
+
through as the route's reply, and adds a `Content-Security-Policy` to an
|
|
118
|
+
IDE page ([GraphiQL and Apollo Sandbox](ide.md)).
|
|
119
|
+
|
|
120
|
+
| Request | Answer |
|
|
121
|
+
| --- | --- |
|
|
122
|
+
| `POST` with `{"query": …}` | `200` and `{"data": …}`, with `errors` beside it when a resolver failed |
|
|
123
|
+
| `GET ?query=…` | the same, for a query; a mutation is a `405` |
|
|
124
|
+
| `POST` a subscription with `Accept: text/event-stream` | `200`, a `text/event-stream` of results ([subscriptions](yoga.md#subscriptions)) |
|
|
125
|
+
| `GET` from a browser (`Accept: text/html`), no `query` | the IDE page; with `ide: false`, a GraphQL answer (`Must provide query string.`) |
|
|
126
|
+
| a hook replied first | that hook's reply, such as a `401` |
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
POST {"query":"{ nope }"} → 200 {"errors":[{"message":"Cannot query field \"nope\" on type \"Query\".", … "extensions":{"code":"GRAPHQL_VALIDATION_FAILED"}}]}
|
|
130
|
+
GET ?query=mutation { m } → 405 {"errors":[{"message":"Can only perform a mutation operation from a POST request.","extensions":{"code":"BAD_REQUEST"}}]}
|
|
131
|
+
POST {} → 200 {"errors":[{"message":"Must provide query string.","extensions":{"code":"BAD_REQUEST"}}]}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The reply's type is `Reply<StatusCode, ReadableStream<Uint8Array> | undefined>`
|
|
135
|
+
for both methods, plus the replies of the hooks before it: a typed client
|
|
136
|
+
sees a body to read as GraphQL, and the guard's `401`.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
type GraphQLRoutes<Path extends string, Shortcuts extends AnyReply> =
|
|
140
|
+
RouteEntryOf<'GET', Path, Empty, GraphQLReply, Shortcuts> &
|
|
141
|
+
RouteEntryOf<'POST', Path, Empty, GraphQLReply, Shortcuts>;
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Testing it
|
|
145
|
+
|
|
146
|
+
The endpoint runs in process through `app.request` or `app.fetch`, like
|
|
147
|
+
every alxia route: no server, no port. `logging: false` keeps Yoga's
|
|
148
|
+
logger quiet in the test output.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
import { describe, expect, test } from 'bun:test';
|
|
152
|
+
import { alxia } from '@alxia/core';
|
|
153
|
+
import { graphql } from '@alxia/graphql';
|
|
154
|
+
import { createSchema } from 'graphql-yoga';
|
|
155
|
+
|
|
156
|
+
const schema = createSchema({
|
|
157
|
+
typeDefs: /* GraphQL */ `type Query { hello(name: String!): String! }`,
|
|
158
|
+
resolvers: { Query: { hello: (_, { name }: { name: string }) => `hello ${name}` } },
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const app = alxia().use((app) => graphql(app, { schema, logging: false }));
|
|
162
|
+
|
|
163
|
+
const execute = (query: string, variables?: Record<string, unknown>) =>
|
|
164
|
+
app.request('/graphql', {
|
|
165
|
+
method: 'POST',
|
|
166
|
+
headers: { 'content-type': 'application/json' },
|
|
167
|
+
body: JSON.stringify({ query, variables }),
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe('graphql', () => {
|
|
171
|
+
test('hello', async () => {
|
|
172
|
+
const response = await execute('query ($name: String!) { hello(name: $name) }', { name: 'Ada' });
|
|
173
|
+
expect(await response.json()).toEqual({ data: { hello: 'hello Ada' } });
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## See also
|
|
179
|
+
|
|
180
|
+
- [The typed context](context.md): what a resolver reads, and the compile
|
|
181
|
+
error when the app does not build it.
|
|
182
|
+
- [Yoga's plugins and options](yoga.md): plugins, errors, subscriptions,
|
|
183
|
+
CORS.
|
|
184
|
+
- [GraphiQL and Apollo Sandbox](ide.md): the page a browser gets.
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# GraphiQL and Apollo Sandbox
|
|
2
|
+
|
|
3
|
+
This page covers what a browser gets when it opens the endpoint — Yoga's
|
|
4
|
+
GraphiQL, Apollo Sandbox, or nothing — their options, the
|
|
5
|
+
`Content-Security-Policy` each loads under, and `renderSandbox` for serving
|
|
6
|
+
the Sandbox yourself.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { alxia } from '@alxia/core';
|
|
10
|
+
import { graphql } from '@alxia/graphql';
|
|
11
|
+
import { createSchema } from 'graphql-yoga';
|
|
12
|
+
|
|
13
|
+
const schema = createSchema({
|
|
14
|
+
typeDefs: /* GraphQL */ `type Query { hello: String! }`,
|
|
15
|
+
resolvers: { Query: { hello: () => 'world' } },
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const app = alxia().use((app) =>
|
|
19
|
+
graphql(app, {
|
|
20
|
+
schema,
|
|
21
|
+
ide: Bun.env['NODE_ENV'] === 'production' ? false : 'apollo-sandbox',
|
|
22
|
+
sandbox: { title: 'Hello API', initialDocument: '{ hello }' },
|
|
23
|
+
}),
|
|
24
|
+
);
|
|
25
|
+
// open http://localhost:3000/graphql in a browser
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## `ide`
|
|
29
|
+
|
|
30
|
+
| `ide` | A browser's `GET` at the endpoint gets | Options |
|
|
31
|
+
| --- | --- | --- |
|
|
32
|
+
| `'graphiql'` (default) | Yoga's GraphiQL | `graphiql` |
|
|
33
|
+
| `'apollo-sandbox'` | [Apollo Sandbox](https://www.apollographql.com/docs/graphos/platform/sandbox), embedded | `sandbox` |
|
|
34
|
+
| `false` | no page: the request is answered as a GraphQL request | — |
|
|
35
|
+
|
|
36
|
+
A `GET` that accepts `text/html` gets the page: GraphiQL with or without a
|
|
37
|
+
`query` parameter (it opens with that query), Apollo Sandbox only without
|
|
38
|
+
one. Every other request is a GraphQL request, answered in JSON. A browser
|
|
39
|
+
sends `*/*` beside `text/html`, so where no page is served — `ide: false`,
|
|
40
|
+
or Sandbox with `?query=` — it gets the JSON result (or
|
|
41
|
+
`Must provide query string.` with no query). A client whose `Accept` allows
|
|
42
|
+
only `text/html` gets a [`406` with an empty
|
|
43
|
+
body](../troubleshooting.md#406-with-an-empty-body) instead.
|
|
44
|
+
|
|
45
|
+
Both IDEs run the schema's introspection and any operation against the
|
|
46
|
+
endpoint, behind the same hooks as every other request: a guard before
|
|
47
|
+
the endpoint guards the page too, and a browser without a token gets the
|
|
48
|
+
guard's reply. Turn the IDE off in production unless you mean to publish
|
|
49
|
+
it.
|
|
50
|
+
|
|
51
|
+
## GraphiQL
|
|
52
|
+
|
|
53
|
+
The default. `graphiql` takes Yoga's `GraphiQLOptions` — not `true` or
|
|
54
|
+
`false`, which `ide` decides:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
graphql(app, {
|
|
58
|
+
schema,
|
|
59
|
+
graphiql: {
|
|
60
|
+
title: 'Users API',
|
|
61
|
+
defaultQuery: '{ me }',
|
|
62
|
+
headers: JSON.stringify({ authorization: 'Bearer <token>' }),
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Its other options — `subscriptionsProtocol`, `credentials`,
|
|
68
|
+
`additionalHeaders`… — are listed in
|
|
69
|
+
[Yoga's GraphiQL documentation](https://the-guild.dev/graphql/yoga-server/docs/features/graphiql).
|
|
70
|
+
|
|
71
|
+
The page loads GraphiQL from `unpkg.com`. Yoga's response has no
|
|
72
|
+
`Content-Security-Policy`, so the package adds one that lets it load:
|
|
73
|
+
|
|
74
|
+
```text
|
|
75
|
+
default-src 'self'; script-src 'self' 'unsafe-inline' https://unpkg.com; style-src 'self' 'unsafe-inline' https://unpkg.com; img-src 'self' data: https:; font-src 'self' data: https:; worker-src 'self' blob:; connect-src 'self'
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Apollo Sandbox
|
|
79
|
+
|
|
80
|
+
`ide: 'apollo-sandbox'` serves a page embedding Apollo Sandbox, pointed at
|
|
81
|
+
the endpoint: the route as served, prefixes included, resolved in the
|
|
82
|
+
browser against the address the page was opened at. Behind a proxy that
|
|
83
|
+
terminates TLS, the Sandbox asks over `https` as the browser did, with no
|
|
84
|
+
option and no `X-Forwarded-Proto`. `sandbox` takes `SandboxOptions`:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
interface SandboxOptions {
|
|
88
|
+
readonly title?: string;
|
|
89
|
+
readonly initialDocument?: string;
|
|
90
|
+
readonly initialHeaders?: Readonly<Record<string, string>>;
|
|
91
|
+
readonly pollForSchemaUpdates?: boolean;
|
|
92
|
+
readonly includeCookies?: boolean;
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Option | Type | Default | Effect |
|
|
97
|
+
| --- | --- | --- | --- |
|
|
98
|
+
| `title` | `string` | `'Sandbox Explorer'` | The page's `<title>`. |
|
|
99
|
+
| `initialDocument` | `string` | none | The operation the Sandbox opens with. |
|
|
100
|
+
| `initialHeaders` | `Record<string, string>` | none | Headers every operation sends, shown and editable in the Sandbox. |
|
|
101
|
+
| `pollForSchemaUpdates` | `boolean` | `true` | Whether the Sandbox polls the schema as it changes. |
|
|
102
|
+
| `includeCookies` | `boolean` | `true` | Whether operations send the browser's cookies, such as a session cookie. |
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
graphql(app, {
|
|
106
|
+
schema,
|
|
107
|
+
ide: 'apollo-sandbox',
|
|
108
|
+
sandbox: {
|
|
109
|
+
title: 'Users API',
|
|
110
|
+
initialDocument: '{ me }',
|
|
111
|
+
initialHeaders: { 'x-tenant': 'acme' },
|
|
112
|
+
includeCookies: false,
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The endpoint shown in the Sandbox is not editable. Every value is escaped
|
|
118
|
+
into the page's HTML and script, so a title or document from configuration
|
|
119
|
+
cannot break out of it.
|
|
120
|
+
|
|
121
|
+
The page loads the Sandbox's script from Apollo's CDN and frames
|
|
122
|
+
`sandbox.embed.apollographql.com`; it is sent with `SANDBOX_POLICY`:
|
|
123
|
+
|
|
124
|
+
```text
|
|
125
|
+
default-src 'self'; script-src 'self' 'unsafe-inline' https://embeddable-sandbox.cdn.apollographql.com; style-src 'self' 'unsafe-inline'; frame-src https://sandbox.embed.apollographql.com; img-src 'self' data: https:; connect-src 'self'
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## With `@alxia/secure-headers`
|
|
129
|
+
|
|
130
|
+
`@alxia/secure-headers` keeps a header a response already has, so the
|
|
131
|
+
IDE's policy survives it and every other route keeps the strict one. A hook
|
|
132
|
+
of your own that **overwrites** `Content-Security-Policy` on every
|
|
133
|
+
response blocks the IDE's scripts, and the page stays blank: set it only
|
|
134
|
+
when the response has none.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { alxia, withHeaders } from '@alxia/core';
|
|
138
|
+
|
|
139
|
+
const app = alxia()
|
|
140
|
+
.onResponse((response) =>
|
|
141
|
+
withHeaders(response, (headers) => {
|
|
142
|
+
if (!headers.has('content-security-policy'))
|
|
143
|
+
headers.set('content-security-policy', "default-src 'self'");
|
|
144
|
+
}),
|
|
145
|
+
)
|
|
146
|
+
.use((app) => graphql(app, { schema }));
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## `renderSandbox`
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
function renderSandbox(endpoint: string, options?: SandboxOptions): string;
|
|
153
|
+
const SANDBOX_POLICY: string;
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The page `ide: 'apollo-sandbox'` serves, as an HTML string, for a Sandbox
|
|
157
|
+
you serve yourself: at another path than the endpoint, or pointed at
|
|
158
|
+
another server. `endpoint` is a URL, or a path the page resolves in the
|
|
159
|
+
browser against its own address — so `'/graphql'` is asked over `https`
|
|
160
|
+
when the page was opened over `https`, proxy or not. Send it with
|
|
161
|
+
`SANDBOX_POLICY`:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
import { alxia } from '@alxia/core';
|
|
165
|
+
import { graphql, renderSandbox, SANDBOX_POLICY } from '@alxia/graphql';
|
|
166
|
+
|
|
167
|
+
const app = alxia()
|
|
168
|
+
.use((app) => graphql(app, { schema, ide: false }))
|
|
169
|
+
.get('/explorer', ({ reply }) =>
|
|
170
|
+
reply(200, renderSandbox('/graphql', { title: 'Users API' }), {
|
|
171
|
+
headers: {
|
|
172
|
+
'content-type': 'text/html;charset=utf-8',
|
|
173
|
+
'content-security-policy': SANDBOX_POLICY,
|
|
174
|
+
},
|
|
175
|
+
}),
|
|
176
|
+
);
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Pass the path the browser sees when a proxy serves the app under one of its
|
|
180
|
+
own — `renderSandbox('/v1/graphql')` — and a full URL for an endpoint on
|
|
181
|
+
another server: `renderSandbox('https://api.example.com/graphql')`.
|
|
182
|
+
|
|
183
|
+
## See also
|
|
184
|
+
|
|
185
|
+
- [Mounting the endpoint](endpoint.md): which hooks run before the page.
|
|
186
|
+
- [Troubleshooting](../troubleshooting.md#the-ide-page-is-blank): a blank IDE page.
|