graphql-http 0.1.0 → 1.0.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.
@@ -0,0 +1,155 @@
1
+ /**
2
+ *
3
+ * handler
4
+ *
5
+ */
6
+ import { ExecutionArgs, ExecutionResult, GraphQLSchema, validate as graphqlValidate, execute as graphqlExecute } from 'graphql';
7
+ import { Request, RequestParams, Response } from './common';
8
+ /**
9
+ * A concrete GraphQL execution context value type.
10
+ *
11
+ * Mainly used because TypeScript collapes unions
12
+ * with `any` or `unknown` to `any` or `unknown`. So,
13
+ * we use a custom type to allow definitions such as
14
+ * the `context` server option.
15
+ *
16
+ * @category Server
17
+ */
18
+ export declare type ExecutionContext = object | symbol | number | string | boolean | undefined | null;
19
+ /** @category Server */
20
+ export interface HandlerOptions<RawRequest = unknown> {
21
+ /**
22
+ * The GraphQL schema on which the operations will
23
+ * be executed and validated against.
24
+ *
25
+ * If a function is provided, it will be called on every
26
+ * operation request allowing you to manipulate schema
27
+ * dynamically.
28
+ *
29
+ * If the schema is left undefined, you're trusted to
30
+ * provide one in the returned `ExecutionArgs` from the
31
+ * `onSubscribe` callback.
32
+ *
33
+ * If you want to respond to the client with a custom status and/or body,
34
+ * you should do by returning a `Request` argument which will stop
35
+ * further execution.
36
+ */
37
+ schema?: GraphQLSchema | ((req: Request<RawRequest>, args: Omit<ExecutionArgs, 'schema'>) => Promise<GraphQLSchema | Response> | GraphQLSchema | Response);
38
+ /**
39
+ * A value which is provided to every resolver and holds
40
+ * important contextual information like the currently
41
+ * logged in user, or access to a database.
42
+ */
43
+ context?: ExecutionContext | ((req: Request<RawRequest>, args: ExecutionArgs) => Promise<ExecutionContext | Response> | ExecutionContext | Response);
44
+ /**
45
+ * A custom GraphQL validate function allowing you to apply your
46
+ * own validation rules.
47
+ */
48
+ validate?: typeof graphqlValidate;
49
+ /**
50
+ * Is the `execute` function from GraphQL which is
51
+ * used to execute the query and mutation operations.
52
+ */
53
+ execute?: typeof graphqlExecute;
54
+ /**
55
+ * The subscribe callback executed right after processing the request
56
+ * before proceeding with the GraphQL operation execution.
57
+ *
58
+ * If you return `ExecutionArgs` from the callback, it will be used instead of
59
+ * trying to build one internally. In this case, you are responsible for providing
60
+ * a ready set of arguments which will be directly plugged in the operation execution.
61
+ *
62
+ * Omitting the fields `contextValue` from the returned `ExecutionArgs` will use the
63
+ * provided `context` option, if available.
64
+ *
65
+ * Useful for preparing the execution arguments following a custom logic. A typical
66
+ * use-case is persisted queries. You can identify the query from the request parameters
67
+ * and supply the appropriate GraphQL operation execution arguments.
68
+ *
69
+ * If you want to respond to the client with a custom status and/or body,
70
+ * you should do by returning a `Request` argument which will stop
71
+ * further execution.
72
+ */
73
+ onSubscribe?: (req: Request<RawRequest>, params: RequestParams) => Promise<ExecutionArgs | Response | void> | ExecutionArgs | Response | void;
74
+ /**
75
+ * Executed after the operation call resolves.
76
+ *
77
+ * The `OperationResult` argument is the result of operation
78
+ * execution. It can be an iterator or already a value.
79
+ *
80
+ * Use this callback to listen for GraphQL operations and
81
+ * execution result manipulation.
82
+ *
83
+ * If you want to respond to the client with a custom status and/or body,
84
+ * you should do by returning a `Request` argument which will stop
85
+ * further execution.
86
+ */
87
+ onOperation?: (req: Request<RawRequest>, args: ExecutionArgs, result: ExecutionResult) => Promise<ExecutionResult | Response | void> | ExecutionResult | Response | void;
88
+ }
89
+ /**
90
+ * The ready-to-use handler. Simply plug it in your favourite HTTP framework
91
+ * and enjoy.
92
+ *
93
+ * Errors thrown from **any** of the provided options or callbacks (or even due to
94
+ * library misuse or potential bugs) will reject the handler's promise. They are
95
+ * considered internal errors and you should take care of them accordingly.
96
+ *
97
+ * @category Server
98
+ */
99
+ export declare type Handler<RawRequest = unknown> = (req: Request<RawRequest>) => Promise<Response>;
100
+ /**
101
+ * Makes a GraphQL over HTTP Protocol compliant server handler. The handler can
102
+ * be used with your favourite server library.
103
+ *
104
+ * Beware that the handler resolves only after the whole operation completes.
105
+ *
106
+ * Errors thrown from **any** of the provided options or callbacks (or even due to
107
+ * library misuse or potential bugs) will reject the handler's promise. They are
108
+ * considered internal errors and you should take care of them accordingly.
109
+ *
110
+ * For production environments, its recommended not to transmit the exact internal
111
+ * error details to the client, but instead report to an error logging tool or simply
112
+ * the console.
113
+ *
114
+ * Simple example usage with Node:
115
+ *
116
+ * ```js
117
+ * import http from 'http';
118
+ * import { createHandler } from 'graphql-http';
119
+ * import { schema } from './my-graphql-schema';
120
+ *
121
+ * // Create the GraphQL over HTTP handler
122
+ * const handler = createHandler({ schema });
123
+ *
124
+ * // Create a HTTP server using the handler on `/graphql`
125
+ * const server = http.createServer(async (req, res) => {
126
+ * if (!req.url.startsWith('/graphql')) {
127
+ * return res.writeHead(404).end();
128
+ * }
129
+ *
130
+ * try {
131
+ * const [body, init] = await handler({
132
+ * url: req.url,
133
+ * method: req.method,
134
+ * headers: req.headers,
135
+ * body: await new Promise((resolve) => {
136
+ * let body = '';
137
+ * req.on('data', (chunk) => (body += chunk));
138
+ * req.on('end', () => resolve(body));
139
+ * }),
140
+ * raw: req,
141
+ * });
142
+ * res.writeHead(init.status, init.statusText, init.headers).end(body);
143
+ * } catch (err) {
144
+ * // BEWARE not to transmit the exact internal error message in production environments
145
+ * res.writeHead(500).end(err.message);
146
+ * }
147
+ * });
148
+ *
149
+ * server.listen(4000);
150
+ * console.log('Listening to port 4000');
151
+ * ```
152
+ *
153
+ * @category Server
154
+ */
155
+ export declare function createHandler<RawRequest = unknown>(options: HandlerOptions<RawRequest>): Handler<RawRequest>;
package/lib/handler.js ADDED
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ /**
3
+ *
4
+ * handler
5
+ *
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createHandler = void 0;
9
+ const graphql_1 = require("graphql");
10
+ const common_1 = require("./common");
11
+ /**
12
+ * Makes a GraphQL over HTTP Protocol compliant server handler. The handler can
13
+ * be used with your favourite server library.
14
+ *
15
+ * Beware that the handler resolves only after the whole operation completes.
16
+ *
17
+ * Errors thrown from **any** of the provided options or callbacks (or even due to
18
+ * library misuse or potential bugs) will reject the handler's promise. They are
19
+ * considered internal errors and you should take care of them accordingly.
20
+ *
21
+ * For production environments, its recommended not to transmit the exact internal
22
+ * error details to the client, but instead report to an error logging tool or simply
23
+ * the console.
24
+ *
25
+ * Simple example usage with Node:
26
+ *
27
+ * ```js
28
+ * import http from 'http';
29
+ * import { createHandler } from 'graphql-http';
30
+ * import { schema } from './my-graphql-schema';
31
+ *
32
+ * // Create the GraphQL over HTTP handler
33
+ * const handler = createHandler({ schema });
34
+ *
35
+ * // Create a HTTP server using the handler on `/graphql`
36
+ * const server = http.createServer(async (req, res) => {
37
+ * if (!req.url.startsWith('/graphql')) {
38
+ * return res.writeHead(404).end();
39
+ * }
40
+ *
41
+ * try {
42
+ * const [body, init] = await handler({
43
+ * url: req.url,
44
+ * method: req.method,
45
+ * headers: req.headers,
46
+ * body: await new Promise((resolve) => {
47
+ * let body = '';
48
+ * req.on('data', (chunk) => (body += chunk));
49
+ * req.on('end', () => resolve(body));
50
+ * }),
51
+ * raw: req,
52
+ * });
53
+ * res.writeHead(init.status, init.statusText, init.headers).end(body);
54
+ * } catch (err) {
55
+ * // BEWARE not to transmit the exact internal error message in production environments
56
+ * res.writeHead(500).end(err.message);
57
+ * }
58
+ * });
59
+ *
60
+ * server.listen(4000);
61
+ * console.log('Listening to port 4000');
62
+ * ```
63
+ *
64
+ * @category Server
65
+ */
66
+ function createHandler(options) {
67
+ const { schema, context, validate = graphql_1.validate, execute = graphql_1.execute, onSubscribe, onOperation, } = options;
68
+ return async function handler(req) {
69
+ var _a, _b;
70
+ const method = req.method;
71
+ if (method !== 'GET' && method !== 'POST') {
72
+ return [
73
+ null,
74
+ {
75
+ status: 405,
76
+ statusText: 'Method Not Allowed',
77
+ headers: {
78
+ allow: 'GET, POST',
79
+ },
80
+ },
81
+ ];
82
+ }
83
+ let acceptedMediaType;
84
+ const accepts = (req.headers.accept || '*/*')
85
+ .replace(/\s/g, '')
86
+ .toLowerCase()
87
+ .split(',');
88
+ for (const accept of accepts) {
89
+ // accept-charset became obsolete, shouldnt be used (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset)
90
+ // TODO: handle the weight parameter "q"
91
+ const [mediaType, ...params] = accept.split(';');
92
+ const charset = (params === null || params === void 0 ? void 0 : params.find((param) => param.includes('charset='))) || 'charset=utf8'; // utf-8 is assumed when not specified;
93
+ if (mediaType === 'application/json' && charset === 'charset=utf8') {
94
+ acceptedMediaType = 'application/json';
95
+ break;
96
+ }
97
+ if ((mediaType === 'application/graphql+json' ||
98
+ mediaType === 'application/*' ||
99
+ mediaType === '*/*') &&
100
+ charset === 'charset=utf8') {
101
+ acceptedMediaType = 'application/graphql+json';
102
+ break;
103
+ }
104
+ }
105
+ if (!acceptedMediaType) {
106
+ return [
107
+ null,
108
+ {
109
+ status: 406,
110
+ statusText: 'Not Acceptable',
111
+ headers: {
112
+ accept: 'application/graphql+json; charset=utf-8, application/json; charset=utf-8',
113
+ },
114
+ },
115
+ ];
116
+ }
117
+ // TODO: should graphql-http care about content-encoding? I'd say unzipping should happen before handler is reached
118
+ const [mediaType, charset = 'charset=utf-8', // utf-8 is assumed when not specified. this parameter is either "charset" or "boundary" (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length)
119
+ ] = (req.headers['content-type'] || '')
120
+ .replace(/\s/g, '')
121
+ .toLowerCase()
122
+ .split(';');
123
+ let params;
124
+ try {
125
+ const partParams = {};
126
+ switch (true) {
127
+ case method === 'GET': {
128
+ // TODO: what if content-type is specified and is not application/x-www-form-urlencoded?
129
+ try {
130
+ const url = new URL(req.url || '', 'http://localhost/');
131
+ partParams.operationName =
132
+ (_a = url.searchParams.get('operationName')) !== null && _a !== void 0 ? _a : undefined;
133
+ partParams.query = (_b = url.searchParams.get('query')) !== null && _b !== void 0 ? _b : undefined;
134
+ const variables = url.searchParams.get('variables');
135
+ if (variables)
136
+ partParams.variables = JSON.parse(variables);
137
+ const extensions = url.searchParams.get('extensions');
138
+ if (extensions)
139
+ partParams.extensions = JSON.parse(extensions);
140
+ }
141
+ catch (_c) {
142
+ throw new Error('Unparsable URL');
143
+ }
144
+ break;
145
+ }
146
+ case method === 'POST' &&
147
+ mediaType === 'application/json' &&
148
+ charset === 'charset=utf-8':
149
+ {
150
+ if (!req.body) {
151
+ throw new Error('Missing body');
152
+ }
153
+ try {
154
+ const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
155
+ partParams.operationName = data.operationName;
156
+ partParams.query = data.query;
157
+ partParams.variables = data.variables;
158
+ partParams.extensions = data.extensions;
159
+ }
160
+ catch (_d) {
161
+ throw new Error('Unparsable JSON body');
162
+ }
163
+ break;
164
+ }
165
+ default: // graphql-http doesnt support any other content type
166
+ return [
167
+ null,
168
+ {
169
+ status: 415,
170
+ statusText: 'Unsupported Media Type',
171
+ },
172
+ ];
173
+ }
174
+ if (!partParams.query)
175
+ throw new Error('Missing query');
176
+ if (partParams.variables != null &&
177
+ (typeof partParams.variables !== 'object' ||
178
+ Array.isArray(partParams.variables))) {
179
+ throw new Error('Invalid variables');
180
+ }
181
+ if (partParams.extensions != null &&
182
+ (typeof partParams.extensions !== 'object' ||
183
+ Array.isArray(partParams.extensions))) {
184
+ throw new Error('Invalid extensions');
185
+ }
186
+ // request parameters are checked and now complete
187
+ params = partParams;
188
+ }
189
+ catch (err) {
190
+ return [
191
+ err.message,
192
+ {
193
+ status: acceptedMediaType === 'application/json' ? 200 : 400,
194
+ statusText: 'Bad Request',
195
+ },
196
+ ];
197
+ }
198
+ let args;
199
+ const maybeResOrExecArgs = await (onSubscribe === null || onSubscribe === void 0 ? void 0 : onSubscribe(req, params));
200
+ if ((0, common_1.isResponse)(maybeResOrExecArgs))
201
+ return maybeResOrExecArgs;
202
+ else if (maybeResOrExecArgs)
203
+ args = maybeResOrExecArgs;
204
+ else {
205
+ if (!schema)
206
+ throw new Error('The GraphQL schema is not provided');
207
+ const { operationName, query, variables } = params;
208
+ let document;
209
+ try {
210
+ document = (0, graphql_1.parse)(query);
211
+ }
212
+ catch (_e) {
213
+ return [
214
+ 'GraphQL query syntax error',
215
+ {
216
+ status: acceptedMediaType === 'application/json' ? 200 : 400,
217
+ statusText: 'Bad Request',
218
+ },
219
+ ];
220
+ }
221
+ const argsWithoutSchema = {
222
+ operationName,
223
+ document,
224
+ variableValues: variables,
225
+ };
226
+ if (typeof schema === 'function') {
227
+ const resOrSchema = await schema(req, argsWithoutSchema);
228
+ if ((0, common_1.isResponse)(resOrSchema))
229
+ return resOrSchema;
230
+ args = Object.assign(Object.assign({}, argsWithoutSchema), { schema: resOrSchema });
231
+ }
232
+ else {
233
+ args = Object.assign(Object.assign({}, argsWithoutSchema), { schema });
234
+ }
235
+ }
236
+ let operation;
237
+ try {
238
+ const ast = (0, graphql_1.getOperationAST)(args.document, args.operationName);
239
+ if (!ast)
240
+ throw null;
241
+ operation = ast.operation;
242
+ }
243
+ catch (_f) {
244
+ return [
245
+ 'Unable to detect operation AST',
246
+ {
247
+ status: acceptedMediaType === 'application/json' ? 200 : 400,
248
+ statusText: 'Bad Request',
249
+ },
250
+ ];
251
+ }
252
+ if (operation === 'subscription') {
253
+ return [
254
+ 'Subscriptions are not supported',
255
+ {
256
+ status: 400,
257
+ statusText: 'Bad Request',
258
+ },
259
+ ];
260
+ }
261
+ // mutations cannot happen over GETs
262
+ // https://graphql.github.io/graphql-over-http/draft/#sel-CALFJRPAAELBAAxwP
263
+ if (operation === 'mutation' && method === 'GET') {
264
+ return [
265
+ 'Cannot perform mutations over GET',
266
+ {
267
+ status: 405,
268
+ statusText: 'Method Not Allowed',
269
+ headers: {
270
+ allow: 'POST',
271
+ },
272
+ },
273
+ ];
274
+ }
275
+ if (!('contextValue' in args)) {
276
+ args.contextValue =
277
+ typeof context === 'function' ? await context(req, args) : context;
278
+ }
279
+ const validationErrs = validate(args.schema, args.document);
280
+ if (validationErrs.length) {
281
+ return [
282
+ JSON.stringify({ errors: validationErrs }),
283
+ {
284
+ status: acceptedMediaType === 'application/json' ? 200 : 400,
285
+ statusText: 'Bad Request',
286
+ headers: {
287
+ 'content-type': acceptedMediaType === 'application/json'
288
+ ? 'application/json; charset=utf-8'
289
+ : 'application/graphql+json; charset=utf-8',
290
+ },
291
+ },
292
+ ];
293
+ }
294
+ let result = await execute(args);
295
+ const maybeResOrResult = await (onOperation === null || onOperation === void 0 ? void 0 : onOperation(req, args, result));
296
+ if ((0, common_1.isResponse)(maybeResOrResult))
297
+ return maybeResOrResult;
298
+ else if (maybeResOrResult)
299
+ result = maybeResOrResult;
300
+ return [
301
+ JSON.stringify(result),
302
+ {
303
+ status: 200,
304
+ statusText: 'OK',
305
+ headers: {
306
+ 'content-type': acceptedMediaType === 'application/json'
307
+ ? 'application/json; charset=utf-8'
308
+ : 'application/graphql+json; charset=utf-8',
309
+ },
310
+ },
311
+ ];
312
+ };
313
+ }
314
+ exports.createHandler = createHandler;