blob: eda251177cbfdeb9671e51009bf2a33325bf43c0 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001var rawBody = require("raw-body")
2var cache = require("continuable-cache")
3
4var parseArguments = require("./parse-arguments.js")
5
6var ONE_MB = 1024 * 1024
7var THUNK_KEY = '__npm_body_thunk_cache__';
8
9module.exports = body
10
11function parseBodyThunk(req, res, opts) {
12 return function thunk(callback) {
13 var limit = "limit" in opts ? opts.limit : ONE_MB
14 var contentLength = req.headers ?
15 Number(req.headers["content-length"]) : null;
16
17 rawBody(req, {
18 limit: limit,
19 length: contentLength,
20 encoding: "encoding" in opts ? opts.encoding : true
21 }, callback);
22 };
23}
24
25function body(req, res, opts, callback) {
26 var args = parseArguments(req, res, opts, callback)
27 req = args.req
28 res = args.res
29 opts = args.opts
30 callback = args.callback
31
32 var thunk;
33
34 if (opts.cache) {
35 var thunk = req[THUNK_KEY] ||
36 cache(parseBodyThunk(req, res, opts));
37 req[THUNK_KEY] = thunk;
38 } else {
39 thunk = parseBodyThunk(req, res, opts);
40 }
41
42 if (!callback) {
43 return thunk;
44 }
45
46 thunk(callback);
47}