-
Notifications
You must be signed in to change notification settings - Fork 5
/
decorate.js
50 lines (43 loc) · 1.1 KB
/
decorate.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
'use strict'
module.exports = Object.assign(decorate, {undecorate, decorations})
const DECORATION = Symbol.for('@npm/decoration')
const DECORATED = Symbol.for('@npm/decorate')
function decorate (inner, wrapper) {
Object.assign(merged, inner)
merged[DECORATED] = inner
merged[DECORATION] = wrapper
Object.defineProperty(merged, 'name', {
get () {
return inner.name
}
})
return merged
function merged (...args) {
return wrapper.call(this, ...args)
}
}
function undecorate (fn) {
return fn[DECORATED] || null
}
function * decorations (fn) {
do {
if (fn[DECORATED]) {
yield * decorations(fn[DECORATION])
} else {
yield fn
}
} while (fn = undecorate(fn))
}
function validateBody (schema, view) {
return decorate(view, (req, context) => {
const args = Array.from(arguments)
return req.body.then(body => {
const result = joi.validate(body, schema)
if (result.error) {
throw new reply.BadRequestError(result.error)
}
req.validatedBody = Promise.resolve(result.value)
return view.apply(this, args)
})
})
}