-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (93 loc) · 1.95 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict'
const fp = require('fastify-plugin')
function fastifyApply (fastify, options, done) {
const hooks = [
'onRequest',
'preParsing',
'preValidation',
'preHandler',
'preSerialization',
'onError',
'onSend',
'onResponse',
'onTimeout',
'onReady',
'onClose',
'onRoute',
'onRegister'
]
hooks.handle = (fastify, prop, value) => {
if (Array.isArray(value)) {
for (const item of value) {
hooks.handle(fastify, prop, item)
}
return
}
fastify.addHook(prop, value)
}
const methods = [
'addHook',
'decorate',
'decorateRequest',
'decorateReply'
]
methods.handle = (fastify, prop, value) => {
for (const [k, v] of Object.entries(value)) {
fastify[prop](k, v)
}
}
const bind = [
'addSchema',
'addHook',
'decorateRequest',
'decorateReply',
'register',
'get',
'head',
'post',
'put',
'delete',
'options',
'patch',
'all'
]
const skip = ['before', 'after', 'encapsulate']
async function apply (obj) {
const wrapper = async function (fastify) {
const proxy = new Proxy(fastify, {
get (_, prop) {
if (bind.includes(prop)) {
return fastify[prop].bind(fastify)
} else {
return fastify[prop]
}
}
})
if (obj.before) {
await obj.before(proxy)
}
for (const [k, v] of Object.entries(obj)) {
if (skip.includes(k)) {
continue
}
if (hooks.includes(k)) {
hooks.handle(fastify, k, v)
}
if (methods.includes(k)) {
methods.handle(fastify, k, v)
}
}
if (obj.after) {
await obj.after(proxy)
}
}
if (obj.encapsulate) {
await fastify.register(wrapper)
} else {
await fastify.register(fp(wrapper))
}
}
fastify.decorate('apply', apply)
done()
}
module.exports = fp(fastifyApply)