-
Notifications
You must be signed in to change notification settings - Fork 10
/
execute.mjs
281 lines (249 loc) · 7.81 KB
/
execute.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// @ts-check
import {
execute as graphqlExecute,
parse,
Source,
specifiedRules,
validate,
} from "graphql";
import createHttpError from "http-errors";
import assertKoaContextRequestGraphQL from "./assertKoaContextRequestGraphQL.mjs";
import checkGraphQLSchema from "./checkGraphQLSchema.mjs";
import checkGraphQLValidationRules from "./checkGraphQLValidationRules.mjs";
import checkOptions from "./checkOptions.mjs";
import GraphQLAggregateError from "./GraphQLAggregateError.mjs";
/**
* List of {@linkcode ExecuteOptions} keys allowed for per request override
* config, for validation purposes.
*/
const ALLOWED_EXECUTE_OPTIONS_OVERRIDE = /** @type {const} */ ([
"schema",
"validationRules",
"rootValue",
"contextValue",
"fieldResolver",
"execute",
]);
/**
* List of {@linkcode ExecuteOptions} keys allowed for static config, for
* validation purposes.
*/
const ALLOWED_EXECUTE_OPTIONS_STATIC = /** @type {const} */ ([
...ALLOWED_EXECUTE_OPTIONS_OVERRIDE,
"override",
]);
/**
* Creates Koa middleware to execute GraphQL. Use after the `errorHandler` and
* [body parser](https://npm.im/koa-bodyparser) middleware.
* @template [KoaContextState=import("koa").DefaultState]
* @template [KoaContext=import("koa").DefaultContext]
* @param {ExecuteOptions & {
* override?: (
* context: import("./assertKoaContextRequestGraphQL.mjs")
* .KoaContextRequestGraphQL<KoaContextState, KoaContext>
* ) => Partial<ExecuteOptions> | Promise<Partial<ExecuteOptions>>,
* }} options Options.
* @returns Koa middleware.
* @example
* A basic GraphQL API:
*
* ```js
* import Koa from "koa";
* import bodyParser from "koa-bodyparser";
* import errorHandler from "graphql-api-koa/errorHandler.mjs";
* import execute from "graphql-api-koa/execute.mjs";
* import schema from "./schema.mjs";
*
* const app = new Koa()
* .use(errorHandler())
* .use(
* bodyParser({
* extendTypes: {
* json: "application/graphql+json",
* },
* })
* )
* .use(execute({ schema }));
* ```
* @example
* {@linkcode execute} middleware options that sets the schema once but
* populates the user in the GraphQL context from the Koa context each request:
*
* ```js
* import schema from "./schema.mjs";
*
* const executeOptions = {
* schema,
* override: (ctx) => ({
* contextValue: {
* user: ctx.state.user,
* },
* }),
* };
* ```
* @example
* An {@linkcode execute} middleware options override that populates the user in
* the GraphQL context from the Koa context:
*
* ```js
* const executeOptionsOverride = (ctx) => ({
* contextValue: {
* user: ctx.state.user,
* },
* });
* ```
*/
export default function execute(options) {
if (typeof options === "undefined")
throw createHttpError(500, "GraphQL execute middleware options missing.");
checkOptions(
options,
ALLOWED_EXECUTE_OPTIONS_STATIC,
"GraphQL execute middleware"
);
if (typeof options.schema !== "undefined")
checkGraphQLSchema(
options.schema,
"GraphQL execute middleware `schema` option"
);
if (typeof options.validationRules !== "undefined")
checkGraphQLValidationRules(
options.validationRules,
"GraphQL execute middleware `validationRules` option"
);
if (
typeof options.execute !== "undefined" &&
typeof options.execute !== "function"
)
throw createHttpError(
500,
"GraphQL execute middleware `execute` option must be a function."
);
const { override, ...staticOptions } = options;
if (typeof override !== "undefined" && typeof override !== "function")
throw createHttpError(
500,
"GraphQL execute middleware `override` option must be a function."
);
/**
* Koa middleware to execute GraphQL.
* @param {import("koa").ParameterizedContext<
* KoaContextState,
* KoaContext
* >} ctx Koa context. The `ctx.request.body` property is conventionally added
* by Koa body parser middleware such as
* [`koa-bodyparser`](https://npm.im/koa-bodyparser).
* @param {() => Promise<unknown>} next
*/
async function executeMiddleware(ctx, next) {
assertKoaContextRequestGraphQL(ctx);
/**
* Parsed GraphQL operation query.
* @type {import("graphql").DocumentNode}
*/
let document;
try {
document = parse(new Source(ctx.request.body.query));
} catch (error) {
throw new GraphQLAggregateError(
[/** @type {import("graphql").GraphQLError} */ (error)],
"GraphQL query syntax errors.",
400,
true
);
}
let overrideOptions;
if (override) {
overrideOptions = await override(ctx);
checkOptions(
overrideOptions,
ALLOWED_EXECUTE_OPTIONS_OVERRIDE,
"GraphQL execute middleware `override` option resolved"
);
if (typeof overrideOptions.schema !== "undefined")
checkGraphQLSchema(
overrideOptions.schema,
"GraphQL execute middleware `override` option resolved `schema` option"
);
if (typeof overrideOptions.validationRules !== "undefined")
checkGraphQLValidationRules(
overrideOptions.validationRules,
"GraphQL execute middleware `override` option resolved `validationRules` option"
);
if (
typeof overrideOptions.execute !== "undefined" &&
typeof overrideOptions.execute !== "function"
)
throw createHttpError(
500,
"GraphQL execute middleware `override` option resolved `execute` option must be a function."
);
}
const requestOptions = {
validationRules: [],
execute: graphqlExecute,
...staticOptions,
...overrideOptions,
};
if (typeof requestOptions.schema === "undefined")
throw createHttpError(
500,
"GraphQL execute middleware requires a GraphQL schema."
);
const queryValidationErrors = validate(requestOptions.schema, document, [
...specifiedRules,
...requestOptions.validationRules,
]);
if (queryValidationErrors.length)
throw new GraphQLAggregateError(
queryValidationErrors,
"GraphQL query validation errors.",
400,
true
);
const { data, errors } = await requestOptions.execute({
schema: requestOptions.schema,
rootValue: requestOptions.rootValue,
contextValue: requestOptions.contextValue,
fieldResolver: requestOptions.fieldResolver,
document,
variableValues: ctx.request.body.variables,
operationName: ctx.request.body.operationName,
});
if (data)
ctx.response.body =
/** @type {import("./errorHandler.mjs").GraphQLResponseBody} */ ({
data,
});
ctx.response.status = 200;
if (errors) {
// By convention GraphQL execution errors shouldn’t result in an error
// HTTP status code.
throw new GraphQLAggregateError(
errors,
"GraphQL execution errors.",
200,
true
);
}
// Set the content-type.
ctx.response.type = "application/graphql+json";
await next();
}
return executeMiddleware;
}
/**
* {@linkcode execute} Koa middleware options.
* @typedef {object} ExecuteOptions
* @prop {import("graphql").GraphQLSchema} schema GraphQL schema.
* @prop {ReadonlyArray<import("graphql").ValidationRule>} [validationRules]
* Validation rules for GraphQL.js {@linkcode validate}, in addition to the
* default GraphQL.js {@linkcode specifiedRules}.
* @prop {any} [rootValue] Value passed to the first resolver.
* @prop {any} [contextValue] Execution context (usually an object) passed to
* resolvers.
* @prop {import("graphql").GraphQLFieldResolver<any, any>} [fieldResolver]
* Custom default field resolver.
* @prop {typeof graphqlExecute} [execute] Replacement for
* [GraphQL.js `execute`](https://graphql.org/graphql-js/execution/#execute).
*/