index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const { parseContentType } = require('./utils.js');
  3. function getInstance(cfg) {
  4. const headers = cfg.headers;
  5. const conType = parseContentType(headers['content-type']);
  6. if (!conType)
  7. throw new Error('Malformed content type');
  8. for (const type of TYPES) {
  9. const matched = type.detect(conType);
  10. if (!matched)
  11. continue;
  12. const instanceCfg = {
  13. limits: cfg.limits,
  14. headers,
  15. conType,
  16. highWaterMark: undefined,
  17. fileHwm: undefined,
  18. defCharset: undefined,
  19. defParamCharset: undefined,
  20. preservePath: false,
  21. };
  22. if (cfg.highWaterMark)
  23. instanceCfg.highWaterMark = cfg.highWaterMark;
  24. if (cfg.fileHwm)
  25. instanceCfg.fileHwm = cfg.fileHwm;
  26. instanceCfg.defCharset = cfg.defCharset;
  27. instanceCfg.defParamCharset = cfg.defParamCharset;
  28. instanceCfg.preservePath = cfg.preservePath;
  29. return new type(instanceCfg);
  30. }
  31. throw new Error(`Unsupported content type: ${headers['content-type']}`);
  32. }
  33. // Note: types are explicitly listed here for easier bundling
  34. // See: https://github.com/mscdex/busboy/issues/121
  35. const TYPES = [
  36. require('./types/multipart'),
  37. require('./types/urlencoded'),
  38. ].filter(function(typemod) { return typeof typemod.detect === 'function'; });
  39. module.exports = (cfg) => {
  40. if (typeof cfg !== 'object' || cfg === null)
  41. cfg = {};
  42. if (typeof cfg.headers !== 'object'
  43. || cfg.headers === null
  44. || typeof cfg.headers['content-type'] !== 'string') {
  45. throw new Error('Missing Content-Type');
  46. }
  47. return getInstance(cfg);
  48. };