| 20 | } |
| 21 | |
| 22 | function getBodyParser(req: NowRequest, body: Buffer | string) { |
| 23 | return function parseBody(): NowRequestBody { |
| 24 | if (!req.headers['content-type']) { |
| 25 | return undefined; |
| 26 | } |
| 27 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 28 | const { parse: parseContentType } = require('content-type'); |
| 29 | const { type } = parseContentType(req.headers['content-type']); |
| 30 | |
| 31 | if (type === 'application/json') { |
| 32 | try { |
| 33 | const str = body.toString(); |
| 34 | return str ? JSON.parse(str) : {}; |
| 35 | } catch (error) { |
| 36 | throw new ApiError(400, 'Invalid JSON'); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | if (type === 'application/octet-stream') { |
| 41 | return body; |
| 42 | } |
| 43 | |
| 44 | if (type === 'application/x-www-form-urlencoded') { |
| 45 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 46 | const { parse: parseQS } = require('querystring'); |
| 47 | // note: querystring.parse does not produce an iterable object |
| 48 | // https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options |
| 49 | return parseQS(body.toString()); |
| 50 | } |
| 51 | |
| 52 | if (type === 'text/plain') { |
| 53 | return body.toString(); |
| 54 | } |
| 55 | |
| 56 | return undefined; |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | function getQueryParser({ url = '/' }: NowRequest) { |
| 61 | return function parseQuery(): NowRequestQuery { |