| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | var TypedError = require("error/typed") |
| 2 | |
| 3 | var parseArguments = require("./parse-arguments.js") |
| 4 | var jsonBody = require("./json.js") |
| 5 | var formBody = require("./form.js") |
| 6 | |
| 7 | var jsonType = "application/json" |
| 8 | var formType = "application/x-www-form-urlencoded" |
| 9 | var INVALID_CONTENT_TYPE = TypedError({ |
| 10 | message: "Could not parse content type header: {contentType}", |
| 11 | type: "invalid.content.type", |
| 12 | statusCode: 415, |
| 13 | contentType: null |
| 14 | }) |
| 15 | |
| 16 | module.exports = anyBody |
| 17 | |
| 18 | function anyBody(req, res, opts, callback) { |
| 19 | var args = parseArguments(req, res, opts, callback) |
| 20 | req = args.req |
| 21 | res = args.res |
| 22 | opts = args.opts |
| 23 | callback = args.callback |
| 24 | |
| 25 | if (!callback) { |
| 26 | return anyBody.bind(null, req, res, opts) |
| 27 | } |
| 28 | |
| 29 | var contentType = req.headers["content-type"] || "" |
| 30 | |
| 31 | if (contentType.indexOf(jsonType) !== -1) { |
| 32 | jsonBody(req, res, opts, callback) |
| 33 | } else if (contentType.indexOf(formType) !== -1) { |
| 34 | formBody(req, res, opts, callback) |
| 35 | } else { |
| 36 | callback(INVALID_CONTENT_TYPE({contentType: contentType})) |
| 37 | } |
| 38 | } |