graphql-http 1.21.0 → 1.22.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.
@@ -1,5 +1,6 @@
1
1
  import type { HttpRequest, HttpResponse } from 'uWebSockets.js';
2
2
  import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handler';
3
+ import { RequestParams } from '../common';
3
4
  /**
4
5
  * The context in the request for the handler.
5
6
  *
@@ -8,6 +9,60 @@ import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handle
8
9
  export interface RequestContext {
9
10
  res: HttpResponse;
10
11
  }
12
+ /**
13
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
14
+ *
15
+ * It is important to pass in the `abortedRef` so that the parser does not perform any
16
+ * operations on a disposed request (see example).
17
+ *
18
+ * If the HTTP request _is not_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), the function will respond
19
+ * on the `HttpResponse` argument and return `null`.
20
+ *
21
+ * If the HTTP request _is_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), but is invalid or malformed,
22
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
23
+ *
24
+ * ```js
25
+ * import uWS from 'uWebSockets.js'; // yarn add uWebSockets.js@uNetworking/uWebSockets.js#<version>
26
+ * import { parseRequestParams } from 'graphql-http/lib/use/uWebSockets';
27
+ *
28
+ * uWS
29
+ * .App()
30
+ * .any('/graphql', async (res, req) => {
31
+ * const abortedRef = { current: false };
32
+ * res.onAborted(() => (abortedRef.current = true));
33
+ * try {
34
+ * const maybeParams = await parseRequestParams(req, res, abortedRef);
35
+ * if (!maybeParams) {
36
+ * // not a well-formatted GraphQL over HTTP request,
37
+ * // parser responded and there's nothing else to do
38
+ * return;
39
+ * }
40
+ *
41
+ * // well-formatted GraphQL over HTTP request,
42
+ * // with valid parameters
43
+ * if (!abortedRef.current) {
44
+ * res.writeStatus('200 OK');
45
+ * res.end(JSON.stringify(maybeParams, null, ' '));
46
+ * }
47
+ * } catch (err) {
48
+ * // well-formatted GraphQL over HTTP request,
49
+ * // but with invalid parameters
50
+ * if (!abortedRef.current) {
51
+ * res.writeStatus('400 Bad Request');
52
+ * res.end(err.message);
53
+ * }
54
+ * }
55
+ * })
56
+ * .listen(4000, () => {
57
+ * console.log('Listening to port 4000');
58
+ * });
59
+ * ```
60
+ *
61
+ * @category Server/uWebSockets
62
+ */
63
+ export declare function parseRequestParams(req: HttpRequest, res: HttpResponse, abortedRef: {
64
+ current: boolean;
65
+ }): Promise<RequestParams | null>;
11
66
  /**
12
67
  * Handler options when using the http adapter.
13
68
  *
@@ -1,7 +1,82 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createHandler = void 0;
3
+ exports.createHandler = exports.parseRequestParams = void 0;
4
4
  const handler_1 = require("../handler");
5
+ /**
6
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
7
+ *
8
+ * It is important to pass in the `abortedRef` so that the parser does not perform any
9
+ * operations on a disposed request (see example).
10
+ *
11
+ * If the HTTP request _is not_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), the function will respond
12
+ * on the `HttpResponse` argument and return `null`.
13
+ *
14
+ * If the HTTP request _is_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), but is invalid or malformed,
15
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
16
+ *
17
+ * ```js
18
+ * import uWS from 'uWebSockets.js'; // yarn add uWebSockets.js@uNetworking/uWebSockets.js#<version>
19
+ * import { parseRequestParams } from 'graphql-http/lib/use/uWebSockets';
20
+ *
21
+ * uWS
22
+ * .App()
23
+ * .any('/graphql', async (res, req) => {
24
+ * const abortedRef = { current: false };
25
+ * res.onAborted(() => (abortedRef.current = true));
26
+ * try {
27
+ * const maybeParams = await parseRequestParams(req, res, abortedRef);
28
+ * if (!maybeParams) {
29
+ * // not a well-formatted GraphQL over HTTP request,
30
+ * // parser responded and there's nothing else to do
31
+ * return;
32
+ * }
33
+ *
34
+ * // well-formatted GraphQL over HTTP request,
35
+ * // with valid parameters
36
+ * if (!abortedRef.current) {
37
+ * res.writeStatus('200 OK');
38
+ * res.end(JSON.stringify(maybeParams, null, ' '));
39
+ * }
40
+ * } catch (err) {
41
+ * // well-formatted GraphQL over HTTP request,
42
+ * // but with invalid parameters
43
+ * if (!abortedRef.current) {
44
+ * res.writeStatus('400 Bad Request');
45
+ * res.end(err.message);
46
+ * }
47
+ * }
48
+ * })
49
+ * .listen(4000, () => {
50
+ * console.log('Listening to port 4000');
51
+ * });
52
+ * ```
53
+ *
54
+ * @category Server/uWebSockets
55
+ */
56
+ async function parseRequestParams(req, res, abortedRef) {
57
+ const rawReq = toRequest(req, res, abortedRef);
58
+ const paramsOrRes = await (0, handler_1.parseRequestParams)(rawReq);
59
+ if (!('query' in paramsOrRes)) {
60
+ if (!abortedRef.current) {
61
+ const [body, init] = paramsOrRes;
62
+ res.cork(() => {
63
+ res.writeStatus(`${init.status} ${init.statusText}`);
64
+ for (const [key, val] of Object.entries(init.headers || {})) {
65
+ res.writeHeader(key, val);
66
+ }
67
+ if (body) {
68
+ res.end(body);
69
+ }
70
+ else {
71
+ res.endWithoutBody();
72
+ }
73
+ });
74
+ }
75
+ return null;
76
+ }
77
+ return paramsOrRes;
78
+ }
79
+ exports.parseRequestParams = parseRequestParams;
5
80
  /**
6
81
  * Create a GraphQL over HTTP spec compliant request handler for
7
82
  * the Node environment [uWebSockets.js module](https://github.com/uNetworking/uWebSockets.js/).
@@ -24,36 +99,11 @@ const handler_1 = require("../handler");
24
99
  function createHandler(options) {
25
100
  const handle = (0, handler_1.createHandler)(options);
26
101
  return async function requestListener(res, req) {
27
- let aborted = false;
28
- res.onAborted(() => (aborted = true));
102
+ const abortedRef = { current: false };
103
+ res.onAborted(() => (abortedRef.current = true));
29
104
  try {
30
- let url = req.getUrl();
31
- const query = req.getQuery();
32
- if (query) {
33
- url += '?' + query;
34
- }
35
- const [body, init] = await handle({
36
- url,
37
- method: req.getMethod().toUpperCase(),
38
- headers: { get: (key) => req.getHeader(key) },
39
- body: () => new Promise((resolve) => {
40
- let body = '';
41
- if (aborted) {
42
- resolve(body);
43
- }
44
- else {
45
- res.onData((chunk, isLast) => {
46
- body += Buffer.from(chunk, 0, chunk.byteLength).toString();
47
- if (isLast) {
48
- resolve(body);
49
- }
50
- });
51
- }
52
- }),
53
- raw: req,
54
- context: { res },
55
- });
56
- if (!aborted) {
105
+ const [body, init] = await handle(toRequest(req, res, abortedRef));
106
+ if (!abortedRef.current) {
57
107
  res.cork(() => {
58
108
  res.writeStatus(`${init.status} ${init.statusText}`);
59
109
  for (const [key, val] of Object.entries(init.headers || {})) {
@@ -73,7 +123,7 @@ function createHandler(options) {
73
123
  // If you wish to handle them differently, consider implementing your own request handler.
74
124
  console.error('Internal error occurred during request handling. ' +
75
125
  'Please check your implementation.', err);
76
- if (!aborted) {
126
+ if (!abortedRef.current) {
77
127
  res.cork(() => {
78
128
  res.writeStatus('500 Internal Server Error').endWithoutBody();
79
129
  });
@@ -82,3 +132,31 @@ function createHandler(options) {
82
132
  };
83
133
  }
84
134
  exports.createHandler = createHandler;
135
+ function toRequest(req, res, abortedRef) {
136
+ let url = req.getUrl();
137
+ const query = req.getQuery();
138
+ if (query) {
139
+ url += '?' + query;
140
+ }
141
+ return {
142
+ url,
143
+ method: req.getMethod().toUpperCase(),
144
+ headers: { get: (key) => req.getHeader(key) },
145
+ body: () => new Promise((resolve) => {
146
+ let body = '';
147
+ if (abortedRef.current) {
148
+ resolve(body);
149
+ }
150
+ else {
151
+ res.onData((chunk, isLast) => {
152
+ body += Buffer.from(chunk, 0, chunk.byteLength).toString();
153
+ if (isLast) {
154
+ resolve(body);
155
+ }
156
+ });
157
+ }
158
+ }),
159
+ raw: req,
160
+ context: { res },
161
+ };
162
+ }
@@ -1,4 +1,78 @@
1
- import { createHandler as createRawHandler, } from '../handler.mjs';
1
+ import { createHandler as createRawHandler, parseRequestParams as rawParseRequestParams, } from '../handler.mjs';
2
+ /**
3
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
4
+ *
5
+ * It is important to pass in the `abortedRef` so that the parser does not perform any
6
+ * operations on a disposed request (see example).
7
+ *
8
+ * If the HTTP request _is not_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), the function will respond
9
+ * on the `HttpResponse` argument and return `null`.
10
+ *
11
+ * If the HTTP request _is_ a [well-formatted GraphQL over HTTP request](https://graphql.github.io/graphql-over-http/draft/#sec-Request), but is invalid or malformed,
12
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
13
+ *
14
+ * ```js
15
+ * import uWS from 'uWebSockets.js'; // yarn add uWebSockets.js@uNetworking/uWebSockets.js#<version>
16
+ * import { parseRequestParams } from 'graphql-http/lib/use/uWebSockets';
17
+ *
18
+ * uWS
19
+ * .App()
20
+ * .any('/graphql', async (res, req) => {
21
+ * const abortedRef = { current: false };
22
+ * res.onAborted(() => (abortedRef.current = true));
23
+ * try {
24
+ * const maybeParams = await parseRequestParams(req, res, abortedRef);
25
+ * if (!maybeParams) {
26
+ * // not a well-formatted GraphQL over HTTP request,
27
+ * // parser responded and there's nothing else to do
28
+ * return;
29
+ * }
30
+ *
31
+ * // well-formatted GraphQL over HTTP request,
32
+ * // with valid parameters
33
+ * if (!abortedRef.current) {
34
+ * res.writeStatus('200 OK');
35
+ * res.end(JSON.stringify(maybeParams, null, ' '));
36
+ * }
37
+ * } catch (err) {
38
+ * // well-formatted GraphQL over HTTP request,
39
+ * // but with invalid parameters
40
+ * if (!abortedRef.current) {
41
+ * res.writeStatus('400 Bad Request');
42
+ * res.end(err.message);
43
+ * }
44
+ * }
45
+ * })
46
+ * .listen(4000, () => {
47
+ * console.log('Listening to port 4000');
48
+ * });
49
+ * ```
50
+ *
51
+ * @category Server/uWebSockets
52
+ */
53
+ export async function parseRequestParams(req, res, abortedRef) {
54
+ const rawReq = toRequest(req, res, abortedRef);
55
+ const paramsOrRes = await rawParseRequestParams(rawReq);
56
+ if (!('query' in paramsOrRes)) {
57
+ if (!abortedRef.current) {
58
+ const [body, init] = paramsOrRes;
59
+ res.cork(() => {
60
+ res.writeStatus(`${init.status} ${init.statusText}`);
61
+ for (const [key, val] of Object.entries(init.headers || {})) {
62
+ res.writeHeader(key, val);
63
+ }
64
+ if (body) {
65
+ res.end(body);
66
+ }
67
+ else {
68
+ res.endWithoutBody();
69
+ }
70
+ });
71
+ }
72
+ return null;
73
+ }
74
+ return paramsOrRes;
75
+ }
2
76
  /**
3
77
  * Create a GraphQL over HTTP spec compliant request handler for
4
78
  * the Node environment [uWebSockets.js module](https://github.com/uNetworking/uWebSockets.js/).
@@ -21,36 +95,11 @@ import { createHandler as createRawHandler, } from '../handler.mjs';
21
95
  export function createHandler(options) {
22
96
  const handle = createRawHandler(options);
23
97
  return async function requestListener(res, req) {
24
- let aborted = false;
25
- res.onAborted(() => (aborted = true));
98
+ const abortedRef = { current: false };
99
+ res.onAborted(() => (abortedRef.current = true));
26
100
  try {
27
- let url = req.getUrl();
28
- const query = req.getQuery();
29
- if (query) {
30
- url += '?' + query;
31
- }
32
- const [body, init] = await handle({
33
- url,
34
- method: req.getMethod().toUpperCase(),
35
- headers: { get: (key) => req.getHeader(key) },
36
- body: () => new Promise((resolve) => {
37
- let body = '';
38
- if (aborted) {
39
- resolve(body);
40
- }
41
- else {
42
- res.onData((chunk, isLast) => {
43
- body += Buffer.from(chunk, 0, chunk.byteLength).toString();
44
- if (isLast) {
45
- resolve(body);
46
- }
47
- });
48
- }
49
- }),
50
- raw: req,
51
- context: { res },
52
- });
53
- if (!aborted) {
101
+ const [body, init] = await handle(toRequest(req, res, abortedRef));
102
+ if (!abortedRef.current) {
54
103
  res.cork(() => {
55
104
  res.writeStatus(`${init.status} ${init.statusText}`);
56
105
  for (const [key, val] of Object.entries(init.headers || {})) {
@@ -70,7 +119,7 @@ export function createHandler(options) {
70
119
  // If you wish to handle them differently, consider implementing your own request handler.
71
120
  console.error('Internal error occurred during request handling. ' +
72
121
  'Please check your implementation.', err);
73
- if (!aborted) {
122
+ if (!abortedRef.current) {
74
123
  res.cork(() => {
75
124
  res.writeStatus('500 Internal Server Error').endWithoutBody();
76
125
  });
@@ -78,3 +127,31 @@ export function createHandler(options) {
78
127
  }
79
128
  };
80
129
  }
130
+ function toRequest(req, res, abortedRef) {
131
+ let url = req.getUrl();
132
+ const query = req.getQuery();
133
+ if (query) {
134
+ url += '?' + query;
135
+ }
136
+ return {
137
+ url,
138
+ method: req.getMethod().toUpperCase(),
139
+ headers: { get: (key) => req.getHeader(key) },
140
+ body: () => new Promise((resolve) => {
141
+ let body = '';
142
+ if (abortedRef.current) {
143
+ resolve(body);
144
+ }
145
+ else {
146
+ res.onData((chunk, isLast) => {
147
+ body += Buffer.from(chunk, 0, chunk.byteLength).toString();
148
+ if (isLast) {
149
+ resolve(body);
150
+ }
151
+ });
152
+ }
153
+ }),
154
+ raw: req,
155
+ context: { res },
156
+ };
157
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "graphql-http",
3
- "version": "1.21.0",
3
+ "version": "1.22.0",
4
4
  "description": "Simple, pluggable, zero-dependency, GraphQL over HTTP spec compliant server, client and audit suite.",
5
5
  "keywords": [
6
6
  "graphql",
@@ -116,43 +116,43 @@
116
116
  "graphql": ">=0.11 <=16"
117
117
  },
118
118
  "devDependencies": {
119
- "@cspell/cspell-types": "^6.31.1",
119
+ "@cspell/cspell-types": "^7.0.0",
120
120
  "@netlify/functions": "^1.6.0",
121
121
  "@rollup/plugin-terser": "^0.4.3",
122
122
  "@rollup/plugin-typescript": "^11.1.2",
123
123
  "@semantic-release/changelog": "^6.0.3",
124
124
  "@semantic-release/git": "^10.0.1",
125
- "@types/eslint": "^8.44.0",
125
+ "@types/eslint": "^8.44.2",
126
126
  "@types/express": "^4.17.17",
127
127
  "@types/glob": "^8.1.0",
128
128
  "@types/html-validator": "^5.0.3",
129
- "@types/k6": "^0.45.0",
130
- "@types/koa": "^2.13.6",
129
+ "@types/k6": "^0.46.0",
130
+ "@types/koa": "^2.13.8",
131
131
  "@types/koa-mount": "^4.0.2",
132
- "@typescript-eslint/eslint-plugin": "^5.61.0",
133
- "@typescript-eslint/parser": "^5.61.0",
134
- "@whatwg-node/fetch": "^0.9.7",
135
- "cspell": "^6.31.1",
136
- "eslint": "^8.44.0",
137
- "eslint-config-prettier": "^8.8.0",
132
+ "@typescript-eslint/eslint-plugin": "^6.4.0",
133
+ "@typescript-eslint/parser": "^6.4.0",
134
+ "@whatwg-node/fetch": "^0.9.9",
135
+ "cspell": "^7.0.0",
136
+ "eslint": "^8.47.0",
137
+ "eslint-config-prettier": "^9.0.0",
138
138
  "express": "^4.18.2",
139
- "fastify": "^4.19.2",
140
- "glob": "^10.3.2",
141
- "graphql": "^16.7.1",
139
+ "fastify": "^4.21.0",
140
+ "glob": "^10.3.3",
141
+ "graphql": "^16.8.0",
142
142
  "html-validator": "^6.0.1",
143
143
  "koa": "^2.14.2",
144
144
  "koa-mount": "^4.0.0",
145
- "node-fetch": "^3.3.1",
146
- "prettier": "^2.8.8",
147
- "rollup": "^3.26.2",
145
+ "node-fetch": "^3.3.2",
146
+ "prettier": "^3.0.1",
147
+ "rollup": "^3.28.0",
148
148
  "rollup-plugin-gzip": "^3.1.0",
149
149
  "semantic-release": "^21.0.7",
150
- "tslib": "^2.6.0",
150
+ "tslib": "^2.6.1",
151
151
  "tsx": "^3.12.7",
152
152
  "typedoc": "^0.24.8",
153
- "typedoc-plugin-markdown": "^3.15.3",
153
+ "typedoc-plugin-markdown": "^3.15.4",
154
154
  "typescript": "^5.1.6",
155
- "uWebSockets.js": "uNetworking/uWebSockets.js#v20.30.0",
156
- "vitest": "^0.33.0"
155
+ "uWebSockets.js": "uNetworking/uWebSockets.js#v20.31.0",
156
+ "vitest": "^0.34.1"
157
157
  }
158
158
  }