index.js 1.1 KB

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