-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (61 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*!
* body-parser
* Copyright(c) 2017 Fangdun Cai <[email protected]> (https://fundon.me)
* MIT Licensed
*/
'use strict'
module.exports = main
const defaults = {
json: true,
urlencoded: true,
skip: false
}
function main(options) {
options = Object.assign({}, defaults, options)
const { skip } = options
if (skip !== false && typeof skip !== 'function') {
throw new TypeError('option skip must be function')
}
const enabled = Object.keys(options).filter(t => options[t])
const parsers = enabled.map(type => main[type](options[type]))
return bodyParser
async function bodyParser(ctx, next) {
if (skip && skip(ctx, options)) return next()
const { req } = ctx
if (undefined !== req.body) return next()
await some(
parsers,
async p => {
const raw = await p(req)
const { bodyParsed } = req
if (bodyParsed) {
req.body = raw
}
return bodyParsed
},
parsers.length,
0
)
return next()
}
}
Object.defineProperties(main, {
busboy: define(() => require('busboy')),
defaults: define(() => defaults),
json: define(getter('json')),
multipart: define(getter('multipart')),
raw: define(getter('raw')),
text: define(getter('text')),
urlencoded: define(getter('urlencoded'))
})
function define(get) {
return { configurable: true, enumerable: true, get }
}
function getter(type) {
return () => require(`./lib/${type}`)
}
async function some(arr, fun, l = 0, i = 0) {
if (i === l) return false
if (await fun(arr[i], i)) return true
return some(arr, fun, l, ++i)
}