1 | 'use strict';
|
2 |
|
3 | const { readdirSync } = require('fs');
|
4 | const { join } = require('path');
|
5 |
|
6 | const { parseContentType } = require('./utils.js');
|
7 |
|
8 | function getInstance(cfg) {
|
9 | const headers = cfg.headers;
|
10 | const conType = parseContentType(headers['content-type']);
|
11 | if (!conType)
|
12 | throw new Error('Malformed content type');
|
13 |
|
14 | for (const type of TYPES) {
|
15 | const matched = type.detect(conType);
|
16 | if (!matched)
|
17 | continue;
|
18 |
|
19 | const instanceCfg = {
|
20 | limits: cfg.limits,
|
21 | headers,
|
22 | conType,
|
23 | highWaterMark: undefined,
|
24 | fileHwm: undefined,
|
25 | defCharset: undefined,
|
26 | preservePath: false,
|
27 | };
|
28 | if (cfg.highWaterMark)
|
29 | instanceCfg.highWaterMark = cfg.highWaterMark;
|
30 | if (cfg.fileHwm)
|
31 | instanceCfg.fileHwm = cfg.fileHwm;
|
32 | instanceCfg.defCharset = cfg.defCharset;
|
33 | instanceCfg.preservePath = cfg.preservePath;
|
34 | return new type(instanceCfg);
|
35 | }
|
36 |
|
37 | throw new Error(`Unsupported content type: ${headers['content-type']}`);
|
38 | }
|
39 |
|
40 | const TYPES = [];
|
41 | for (const file of readdirSync(join(__dirname, 'types'))) {
|
42 | if (/\.js$/i.test(file)) {
|
43 | const type = require(`./types/${file}`);
|
44 | if (type && typeof type.detect === 'function')
|
45 | TYPES.push(type);
|
46 | }
|
47 | }
|
48 |
|
49 | module.exports = (cfg) => {
|
50 | if (typeof cfg !== 'object' || cfg === null)
|
51 | cfg = {};
|
52 |
|
53 | if (typeof cfg.headers !== 'object'
|
54 | || cfg.headers === null
|
55 | || typeof cfg.headers['content-type'] !== 'string') {
|
56 | throw new Error('Missing Content-Type');
|
57 | }
|
58 |
|
59 | return getInstance(cfg);
|
60 | };
|