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,6 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import type { Http2ServerRequest, Http2ServerResponse } from 'http2';
3
3
  import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handler';
4
+ import { RequestParams } from '../common';
4
5
  /**
5
6
  * The context in the request for the handler.
6
7
  *
@@ -9,6 +10,61 @@ import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handle
9
10
  export interface RequestContext {
10
11
  res: Http2ServerResponse;
11
12
  }
13
+ /**
14
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
15
+ *
16
+ * 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
17
+ * on the `Http2ServerResponse` argument and return `null`.
18
+ *
19
+ * 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,
20
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
21
+ *
22
+ * ```shell
23
+ * $ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
24
+ * -keyout localhost-privkey.pem -out localhost-cert.pem
25
+ * ```
26
+ *
27
+ * ```js
28
+ * import fs from 'fs';
29
+ * import http2 from 'http2';
30
+ * import { parseRequestParams } from 'graphql-http/lib/use/http2';
31
+ *
32
+ * const server = http2.createSecureServer(
33
+ * {
34
+ * key: fs.readFileSync('localhost-privkey.pem'),
35
+ * cert: fs.readFileSync('localhost-cert.pem'),
36
+ * },
37
+ * async (req, res) => {
38
+ * if (req.url.startsWith('/graphql')) {
39
+ * try {
40
+ * const maybeParams = await parseRequestParams(req, res);
41
+ * if (!maybeParams) {
42
+ * // not a well-formatted GraphQL over HTTP request,
43
+ * // parser responded and there's nothing else to do
44
+ * return;
45
+ * }
46
+ *
47
+ * // well-formatted GraphQL over HTTP request,
48
+ * // with valid parameters
49
+ * res.writeHead(200).end(JSON.stringify(maybeParams, null, ' '));
50
+ * } catch (err) {
51
+ * // well-formatted GraphQL over HTTP request,
52
+ * // but with invalid parameters
53
+ * res.writeHead(400).end(err.message);
54
+ * }
55
+ * } else {
56
+ * res.writeHead(404).end();
57
+ * }
58
+ * },
59
+ * );
60
+ *
61
+ * server.listen(4000);
62
+ * console.log('Listening to port 4000');
63
+ * ```
64
+ *
65
+ * @category Server/http2
66
+ */
67
+ export declare function parseRequestParams(req: Http2ServerRequest, res: Http2ServerResponse): Promise<RequestParams | null>;
12
68
  /**
13
69
  * Handler options when using the http adapter.
14
70
  *
package/lib/use/http2.js CHANGED
@@ -1,7 +1,78 @@
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
+ * 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 `Http2ServerResponse` 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
+ * ```shell
15
+ * $ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
16
+ * -keyout localhost-privkey.pem -out localhost-cert.pem
17
+ * ```
18
+ *
19
+ * ```js
20
+ * import fs from 'fs';
21
+ * import http2 from 'http2';
22
+ * import { parseRequestParams } from 'graphql-http/lib/use/http2';
23
+ *
24
+ * const server = http2.createSecureServer(
25
+ * {
26
+ * key: fs.readFileSync('localhost-privkey.pem'),
27
+ * cert: fs.readFileSync('localhost-cert.pem'),
28
+ * },
29
+ * async (req, res) => {
30
+ * if (req.url.startsWith('/graphql')) {
31
+ * try {
32
+ * const maybeParams = await parseRequestParams(req, res);
33
+ * if (!maybeParams) {
34
+ * // not a well-formatted GraphQL over HTTP request,
35
+ * // parser responded and there's nothing else to do
36
+ * return;
37
+ * }
38
+ *
39
+ * // well-formatted GraphQL over HTTP request,
40
+ * // with valid parameters
41
+ * res.writeHead(200).end(JSON.stringify(maybeParams, null, ' '));
42
+ * } catch (err) {
43
+ * // well-formatted GraphQL over HTTP request,
44
+ * // but with invalid parameters
45
+ * res.writeHead(400).end(err.message);
46
+ * }
47
+ * } else {
48
+ * res.writeHead(404).end();
49
+ * }
50
+ * },
51
+ * );
52
+ *
53
+ * server.listen(4000);
54
+ * console.log('Listening to port 4000');
55
+ * ```
56
+ *
57
+ * @category Server/http2
58
+ */
59
+ async function parseRequestParams(req, res) {
60
+ const rawReq = toRequest(req, res);
61
+ const paramsOrRes = await (0, handler_1.parseRequestParams)(rawReq);
62
+ if (!('query' in paramsOrRes)) {
63
+ const [body, init] = paramsOrRes;
64
+ res.writeHead(init.status, init.statusText, init.headers);
65
+ if (body) {
66
+ res.end(body);
67
+ }
68
+ else {
69
+ res.end();
70
+ }
71
+ return null;
72
+ }
73
+ return paramsOrRes;
74
+ }
75
+ exports.parseRequestParams = parseRequestParams;
5
76
  /**
6
77
  * Create a GraphQL over HTTP spec compliant request handler for
7
78
  * the Node environment http2 module.
@@ -41,18 +112,7 @@ function createHandler(options) {
41
112
  if (!req.method) {
42
113
  throw new Error('Missing request method');
43
114
  }
44
- const [body, init] = await handle({
45
- url: req.url,
46
- method: req.method,
47
- headers: req.headers,
48
- body: () => new Promise((resolve) => {
49
- let body = '';
50
- req.on('data', (chunk) => (body += chunk));
51
- req.on('end', () => resolve(body));
52
- }),
53
- raw: req,
54
- context: { res },
55
- });
115
+ const [body, init] = await handle(toRequest(req, res));
56
116
  res.writeHead(init.status, init.statusText, init.headers);
57
117
  if (body) {
58
118
  res.end(body);
@@ -71,3 +131,23 @@ function createHandler(options) {
71
131
  };
72
132
  }
73
133
  exports.createHandler = createHandler;
134
+ function toRequest(req, res) {
135
+ if (!req.url) {
136
+ throw new Error('Missing request URL');
137
+ }
138
+ if (!req.method) {
139
+ throw new Error('Missing request method');
140
+ }
141
+ return {
142
+ url: req.url,
143
+ method: req.method,
144
+ headers: req.headers,
145
+ body: () => new Promise((resolve) => {
146
+ let body = '';
147
+ req.on('data', (chunk) => (body += chunk));
148
+ req.on('end', () => resolve(body));
149
+ }),
150
+ raw: req,
151
+ context: { res },
152
+ };
153
+ }
package/lib/use/http2.mjs CHANGED
@@ -1,4 +1,74 @@
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
+ * 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
6
+ * on the `Http2ServerResponse` argument and return `null`.
7
+ *
8
+ * 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,
9
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
10
+ *
11
+ * ```shell
12
+ * $ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
13
+ * -keyout localhost-privkey.pem -out localhost-cert.pem
14
+ * ```
15
+ *
16
+ * ```js
17
+ * import fs from 'fs';
18
+ * import http2 from 'http2';
19
+ * import { parseRequestParams } from 'graphql-http/lib/use/http2';
20
+ *
21
+ * const server = http2.createSecureServer(
22
+ * {
23
+ * key: fs.readFileSync('localhost-privkey.pem'),
24
+ * cert: fs.readFileSync('localhost-cert.pem'),
25
+ * },
26
+ * async (req, res) => {
27
+ * if (req.url.startsWith('/graphql')) {
28
+ * try {
29
+ * const maybeParams = await parseRequestParams(req, res);
30
+ * if (!maybeParams) {
31
+ * // not a well-formatted GraphQL over HTTP request,
32
+ * // parser responded and there's nothing else to do
33
+ * return;
34
+ * }
35
+ *
36
+ * // well-formatted GraphQL over HTTP request,
37
+ * // with valid parameters
38
+ * res.writeHead(200).end(JSON.stringify(maybeParams, null, ' '));
39
+ * } catch (err) {
40
+ * // well-formatted GraphQL over HTTP request,
41
+ * // but with invalid parameters
42
+ * res.writeHead(400).end(err.message);
43
+ * }
44
+ * } else {
45
+ * res.writeHead(404).end();
46
+ * }
47
+ * },
48
+ * );
49
+ *
50
+ * server.listen(4000);
51
+ * console.log('Listening to port 4000');
52
+ * ```
53
+ *
54
+ * @category Server/http2
55
+ */
56
+ export async function parseRequestParams(req, res) {
57
+ const rawReq = toRequest(req, res);
58
+ const paramsOrRes = await rawParseRequestParams(rawReq);
59
+ if (!('query' in paramsOrRes)) {
60
+ const [body, init] = paramsOrRes;
61
+ res.writeHead(init.status, init.statusText, init.headers);
62
+ if (body) {
63
+ res.end(body);
64
+ }
65
+ else {
66
+ res.end();
67
+ }
68
+ return null;
69
+ }
70
+ return paramsOrRes;
71
+ }
2
72
  /**
3
73
  * Create a GraphQL over HTTP spec compliant request handler for
4
74
  * the Node environment http2 module.
@@ -38,18 +108,7 @@ export function createHandler(options) {
38
108
  if (!req.method) {
39
109
  throw new Error('Missing request method');
40
110
  }
41
- const [body, init] = await handle({
42
- url: req.url,
43
- method: req.method,
44
- headers: req.headers,
45
- body: () => new Promise((resolve) => {
46
- let body = '';
47
- req.on('data', (chunk) => (body += chunk));
48
- req.on('end', () => resolve(body));
49
- }),
50
- raw: req,
51
- context: { res },
52
- });
111
+ const [body, init] = await handle(toRequest(req, res));
53
112
  res.writeHead(init.status, init.statusText, init.headers);
54
113
  if (body) {
55
114
  res.end(body);
@@ -67,3 +126,23 @@ export function createHandler(options) {
67
126
  }
68
127
  };
69
128
  }
129
+ function toRequest(req, res) {
130
+ if (!req.url) {
131
+ throw new Error('Missing request URL');
132
+ }
133
+ if (!req.method) {
134
+ throw new Error('Missing request method');
135
+ }
136
+ return {
137
+ url: req.url,
138
+ method: req.method,
139
+ headers: req.headers,
140
+ body: () => new Promise((resolve) => {
141
+ let body = '';
142
+ req.on('data', (chunk) => (body += chunk));
143
+ req.on('end', () => resolve(body));
144
+ }),
145
+ raw: req,
146
+ context: { res },
147
+ };
148
+ }
package/lib/use/koa.d.mts CHANGED
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
- import type { Middleware, Response } from 'koa';
2
+ import type { Middleware, ParameterizedContext, Response } from 'koa';
3
3
  import type { IncomingMessage } from 'http';
4
4
  import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handler.mjs';
5
+ import { RequestParams } from '../common.mjs';
5
6
  /**
6
7
  * The context in the request for the handler.
7
8
  *
@@ -10,6 +11,51 @@ import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handle
10
11
  export interface RequestContext {
11
12
  res: Response;
12
13
  }
14
+ /**
15
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
16
+ *
17
+ * 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
18
+ * on Koa's `ParameterizedContext` response and return `null`.
19
+ *
20
+ * 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,
21
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
22
+ *
23
+ * ```js
24
+ * import Koa from 'koa'; // yarn add koa
25
+ * import mount from 'koa-mount'; // yarn add koa-mount
26
+ * import { parseRequestParams } from 'graphql-http/lib/use/koa';
27
+ *
28
+ * const app = new Koa();
29
+ * app.use(
30
+ * mount('/', async (ctx) => {
31
+ * try {
32
+ * const maybeParams = await parseRequestParams(ctx);
33
+ * if (!maybeParams) {
34
+ * // not a well-formatted GraphQL over HTTP request,
35
+ * // parser responded and there's nothing else to do
36
+ * return;
37
+ * }
38
+ *
39
+ * // well-formatted GraphQL over HTTP request,
40
+ * // with valid parameters
41
+ * ctx.response.status = 200;
42
+ * ctx.body = JSON.stringify(maybeParams, null, ' ');
43
+ * } catch (err) {
44
+ * // well-formatted GraphQL over HTTP request,
45
+ * // but with invalid parameters
46
+ * ctx.response.status = 400;
47
+ * ctx.body = err.message;
48
+ * }
49
+ * }),
50
+ * );
51
+ *
52
+ * app.listen({ port: 4000 });
53
+ * console.log('Listening to port 4000');
54
+ * ```
55
+ *
56
+ * @category Server/koa
57
+ */
58
+ export declare function parseRequestParams(ctx: ParameterizedContext): Promise<RequestParams | null>;
13
59
  /**
14
60
  * Handler options when using the koa adapter.
15
61
  *
package/lib/use/koa.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
- import type { Middleware, Response } from 'koa';
2
+ import type { Middleware, ParameterizedContext, Response } from 'koa';
3
3
  import type { IncomingMessage } from 'http';
4
4
  import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handler';
5
+ import { RequestParams } from '../common';
5
6
  /**
6
7
  * The context in the request for the handler.
7
8
  *
@@ -10,6 +11,51 @@ import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handle
10
11
  export interface RequestContext {
11
12
  res: Response;
12
13
  }
14
+ /**
15
+ * The GraphQL over HTTP spec compliant request parser for an incoming GraphQL request.
16
+ *
17
+ * 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
18
+ * on Koa's `ParameterizedContext` response and return `null`.
19
+ *
20
+ * 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,
21
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
22
+ *
23
+ * ```js
24
+ * import Koa from 'koa'; // yarn add koa
25
+ * import mount from 'koa-mount'; // yarn add koa-mount
26
+ * import { parseRequestParams } from 'graphql-http/lib/use/koa';
27
+ *
28
+ * const app = new Koa();
29
+ * app.use(
30
+ * mount('/', async (ctx) => {
31
+ * try {
32
+ * const maybeParams = await parseRequestParams(ctx);
33
+ * if (!maybeParams) {
34
+ * // not a well-formatted GraphQL over HTTP request,
35
+ * // parser responded and there's nothing else to do
36
+ * return;
37
+ * }
38
+ *
39
+ * // well-formatted GraphQL over HTTP request,
40
+ * // with valid parameters
41
+ * ctx.response.status = 200;
42
+ * ctx.body = JSON.stringify(maybeParams, null, ' ');
43
+ * } catch (err) {
44
+ * // well-formatted GraphQL over HTTP request,
45
+ * // but with invalid parameters
46
+ * ctx.response.status = 400;
47
+ * ctx.body = err.message;
48
+ * }
49
+ * }),
50
+ * );
51
+ *
52
+ * app.listen({ port: 4000 });
53
+ * console.log('Listening to port 4000');
54
+ * ```
55
+ *
56
+ * @category Server/koa
57
+ */
58
+ export declare function parseRequestParams(ctx: ParameterizedContext): Promise<RequestParams | null>;
13
59
  /**
14
60
  * Handler options when using the koa adapter.
15
61
  *
package/lib/use/koa.js CHANGED
@@ -1,7 +1,69 @@
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
+ * 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 Koa's `ParameterizedContext` response 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 Koa from 'koa'; // yarn add koa
16
+ * import mount from 'koa-mount'; // yarn add koa-mount
17
+ * import { parseRequestParams } from 'graphql-http/lib/use/koa';
18
+ *
19
+ * const app = new Koa();
20
+ * app.use(
21
+ * mount('/', async (ctx) => {
22
+ * try {
23
+ * const maybeParams = await parseRequestParams(ctx);
24
+ * if (!maybeParams) {
25
+ * // not a well-formatted GraphQL over HTTP request,
26
+ * // parser responded and there's nothing else to do
27
+ * return;
28
+ * }
29
+ *
30
+ * // well-formatted GraphQL over HTTP request,
31
+ * // with valid parameters
32
+ * ctx.response.status = 200;
33
+ * ctx.body = JSON.stringify(maybeParams, null, ' ');
34
+ * } catch (err) {
35
+ * // well-formatted GraphQL over HTTP request,
36
+ * // but with invalid parameters
37
+ * ctx.response.status = 400;
38
+ * ctx.body = err.message;
39
+ * }
40
+ * }),
41
+ * );
42
+ *
43
+ * app.listen({ port: 4000 });
44
+ * console.log('Listening to port 4000');
45
+ * ```
46
+ *
47
+ * @category Server/koa
48
+ */
49
+ async function parseRequestParams(ctx) {
50
+ const rawReq = toRequest(ctx);
51
+ const paramsOrRes = await (0, handler_1.parseRequestParams)(rawReq);
52
+ if (!('query' in paramsOrRes)) {
53
+ const [body, init] = paramsOrRes;
54
+ ctx.body = body;
55
+ ctx.response.status = init.status;
56
+ ctx.response.message = init.statusText;
57
+ if (init.headers) {
58
+ for (const [name, value] of Object.entries(init.headers)) {
59
+ ctx.response.set(name, value);
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ return paramsOrRes;
65
+ }
66
+ exports.parseRequestParams = parseRequestParams;
5
67
  /**
6
68
  * Create a GraphQL over HTTP spec compliant request handler for
7
69
  * the Koa framework.
@@ -62,3 +124,24 @@ function createHandler(options) {
62
124
  };
63
125
  }
64
126
  exports.createHandler = createHandler;
127
+ function toRequest(ctx) {
128
+ return {
129
+ url: ctx.url,
130
+ method: ctx.method,
131
+ headers: ctx.headers,
132
+ body: () => {
133
+ if (ctx.body) {
134
+ // in case koa has a body parser
135
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
136
+ return ctx.body;
137
+ }
138
+ return new Promise((resolve) => {
139
+ let body = '';
140
+ ctx.req.on('data', (chunk) => (body += chunk));
141
+ ctx.req.on('end', () => resolve(body));
142
+ });
143
+ },
144
+ raw: ctx.req,
145
+ context: { res: ctx.response },
146
+ };
147
+ }
package/lib/use/koa.mjs CHANGED
@@ -1,4 +1,65 @@
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
+ * 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
6
+ * on Koa's `ParameterizedContext` response and return `null`.
7
+ *
8
+ * 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,
9
+ * the function will throw an error and it is up to the user to handle and respond as they see fit.
10
+ *
11
+ * ```js
12
+ * import Koa from 'koa'; // yarn add koa
13
+ * import mount from 'koa-mount'; // yarn add koa-mount
14
+ * import { parseRequestParams } from 'graphql-http/lib/use/koa';
15
+ *
16
+ * const app = new Koa();
17
+ * app.use(
18
+ * mount('/', async (ctx) => {
19
+ * try {
20
+ * const maybeParams = await parseRequestParams(ctx);
21
+ * if (!maybeParams) {
22
+ * // not a well-formatted GraphQL over HTTP request,
23
+ * // parser responded and there's nothing else to do
24
+ * return;
25
+ * }
26
+ *
27
+ * // well-formatted GraphQL over HTTP request,
28
+ * // with valid parameters
29
+ * ctx.response.status = 200;
30
+ * ctx.body = JSON.stringify(maybeParams, null, ' ');
31
+ * } catch (err) {
32
+ * // well-formatted GraphQL over HTTP request,
33
+ * // but with invalid parameters
34
+ * ctx.response.status = 400;
35
+ * ctx.body = err.message;
36
+ * }
37
+ * }),
38
+ * );
39
+ *
40
+ * app.listen({ port: 4000 });
41
+ * console.log('Listening to port 4000');
42
+ * ```
43
+ *
44
+ * @category Server/koa
45
+ */
46
+ export async function parseRequestParams(ctx) {
47
+ const rawReq = toRequest(ctx);
48
+ const paramsOrRes = await rawParseRequestParams(rawReq);
49
+ if (!('query' in paramsOrRes)) {
50
+ const [body, init] = paramsOrRes;
51
+ ctx.body = body;
52
+ ctx.response.status = init.status;
53
+ ctx.response.message = init.statusText;
54
+ if (init.headers) {
55
+ for (const [name, value] of Object.entries(init.headers)) {
56
+ ctx.response.set(name, value);
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+ return paramsOrRes;
62
+ }
2
63
  /**
3
64
  * Create a GraphQL over HTTP spec compliant request handler for
4
65
  * the Koa framework.
@@ -58,3 +119,24 @@ export function createHandler(options) {
58
119
  }
59
120
  };
60
121
  }
122
+ function toRequest(ctx) {
123
+ return {
124
+ url: ctx.url,
125
+ method: ctx.method,
126
+ headers: ctx.headers,
127
+ body: () => {
128
+ if (ctx.body) {
129
+ // in case koa has a body parser
130
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
131
+ return ctx.body;
132
+ }
133
+ return new Promise((resolve) => {
134
+ let body = '';
135
+ ctx.req.on('data', (chunk) => (body += chunk));
136
+ ctx.req.on('end', () => resolve(body));
137
+ });
138
+ },
139
+ raw: ctx.req,
140
+ context: { res: ctx.response },
141
+ };
142
+ }
@@ -1,5 +1,6 @@
1
1
  import type { HttpRequest, HttpResponse } from 'uWebSockets.js';
2
2
  import { HandlerOptions as RawHandlerOptions, OperationContext } from '../handler.mjs';
3
+ import { RequestParams } from '../common.mjs';
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
  *