any.js 1.0 KB

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