isEligibleRequest.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. const ACCEPTABLE_CONTENT_TYPE = /^(multipart\/.+);(.*)$/i;
  2. const UNACCEPTABLE_METHODS = ['GET', 'HEAD'];
  3. /**
  4. * Ensures the request contains a content body
  5. * @param {Object} req Express req object
  6. * @returns {Boolean}
  7. */
  8. const hasBody = (req) => {
  9. return ('transfer-encoding' in req.headers) ||
  10. ('content-length' in req.headers && req.headers['content-length'] !== '0');
  11. };
  12. /**
  13. * Ensures the request is not using a non-compliant multipart method
  14. * such as GET or HEAD
  15. * @param {Object} req Express req object
  16. * @returns {Boolean}
  17. */
  18. const hasAcceptableMethod = req => !UNACCEPTABLE_METHODS.includes(req.method);
  19. /**
  20. * Ensures that only multipart requests are processed by express-fileupload
  21. * @param {Object} req Express req object
  22. * @returns {Boolean}
  23. */
  24. const hasAcceptableContentType = req => ACCEPTABLE_CONTENT_TYPE.test(req.headers['content-type']);
  25. /**
  26. * Ensures that the request in question is eligible for file uploads
  27. * @param {Object} req Express req object
  28. * @returns {Boolean}
  29. */
  30. module.exports = req => hasBody(req) && hasAcceptableMethod(req) && hasAcceptableContentType(req);