MCPcopy Create free account
hub / github.com/ctrlplusb/vercel-node-server / getBodyParser

Function getBodyParser

src/index.ts:22–58  ·  view source on GitHub ↗
(req: NowRequest, body: Buffer | string)

Source from the content-addressed store, hash-verified

20}
21
22function 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
60function getQueryParser({ url = '/' }: NowRequest) {
61 return function parseQuery(): NowRequestQuery {

Callers 1

enhanceRequestFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected