123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- import type { IncomingMessage } from 'http';
- import type { Inflate, Gunzip } from 'zlib';
- import zlib from 'zlib';
- import querystring from 'querystring';
- import getBody from 'raw-body';
- import httpError from 'http-errors';
- import contentType from 'content-type';
- type $Request = IncomingMessage & { body?: mixed, ... };
- export async function parseBody(
- req: $Request,
- ): Promise<{ [param: string]: mixed, ... }> {
- const { body } = req;
-
- if (typeof body === 'object' && !(body instanceof Buffer)) {
- return (body: any);
- }
-
- if (req.headers['content-type'] === undefined) {
- return {};
- }
- const typeInfo = contentType.parse(req);
-
-
- if (typeof body === 'string' && typeInfo.type === 'application/graphql') {
- return { query: body };
- }
-
- if (body != null) {
- return {};
- }
- const rawBody = await readBody(req, typeInfo);
-
- switch (typeInfo.type) {
- case 'application/graphql':
- return { query: rawBody };
- case 'application/json':
- if (jsonObjRegex.test(rawBody)) {
- try {
- return JSON.parse(rawBody);
- } catch (error) {
-
- }
- }
- throw httpError(400, 'POST body sent invalid JSON.');
- case 'application/x-www-form-urlencoded':
- return querystring.parse(rawBody);
- }
-
- return {};
- }
- const jsonObjRegex = /^[ \t\n\r]*\{/;
- async function readBody(
- req: $Request,
-
- typeInfo: {| type: string, parameters: { [param: string]: string, ... } |},
- ): Promise<string> {
-
- const charset = typeInfo.parameters.charset?.toLowerCase() ?? 'utf-8';
-
- if (charset.slice(0, 4) !== 'utf-') {
- throw httpError(415, `Unsupported charset "${charset.toUpperCase()}".`);
- }
-
- const contentEncoding = req.headers['content-encoding'];
- const encoding =
- typeof contentEncoding === 'string'
- ? contentEncoding.toLowerCase()
- : 'identity';
- const length = encoding === 'identity' ? req.headers['content-length'] : null;
- const limit = 100 * 1024;
- const stream = decompressed(req, encoding);
-
- try {
- return await getBody(stream, { encoding: charset, length, limit });
- } catch (err) {
- throw err.type === 'encoding.unsupported'
- ? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`)
- : httpError(400, `Invalid body: ${err.message}.`);
- }
- }
- function decompressed(
- req: $Request,
- encoding: string,
- ): $Request | Inflate | Gunzip {
- switch (encoding) {
- case 'identity':
- return req;
- case 'deflate':
- return req.pipe(zlib.createInflate());
- case 'gzip':
- return req.pipe(zlib.createGunzip());
- }
- throw httpError(415, `Unsupported content-encoding "${encoding}".`);
- }
|