-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
106 lines (91 loc) · 2.66 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
104
105
106
'use strict'
const fp = require('fastify-plugin')
const Middie = require('./lib/engine')
const kMiddlewares = Symbol('fastify-middie-middlewares')
const kMiddie = Symbol('fastify-middie-instance')
const kMiddieHasMiddlewares = Symbol('fastify-middie-has-middlewares')
const { FST_ERR_MIDDIE_INVALID_HOOK } = require('./lib/errors')
const supportedHooksWithPayload = [
'onError',
'onSend',
'preParsing',
'preSerialization'
]
const supportedHooksWithoutPayload = [
'onRequest',
'onResponse',
'onTimeout',
'preHandler',
'preValidation'
]
const supportedHooks = [...supportedHooksWithPayload, ...supportedHooksWithoutPayload]
function fastifyMiddie (fastify, options, next) {
fastify.decorate('use', use)
fastify[kMiddlewares] = []
fastify[kMiddieHasMiddlewares] = false
fastify[kMiddie] = Middie(onMiddieEnd)
const hook = options.hook || 'onRequest'
if (!supportedHooks.includes(hook)) {
next(new FST_ERR_MIDDIE_INVALID_HOOK(hook))
return
}
fastify
.addHook(hook, supportedHooksWithPayload.includes(hook)
? runMiddieWithPayload
: runMiddie)
.addHook('onRegister', onRegister)
function use (path, fn) {
if (typeof path === 'string') {
const prefix = this.prefix
path = prefix + (path === '/' && prefix.length > 0 ? '' : path)
}
this[kMiddlewares].push([path, fn])
if (fn == null) {
this[kMiddie].use(path)
} else {
this[kMiddie].use(path, fn)
}
this[kMiddieHasMiddlewares] = true
return this
}
function runMiddie (req, reply, next) {
if (this[kMiddieHasMiddlewares]) {
req.raw.originalUrl = req.raw.url
req.raw.id = req.id
req.raw.hostname = req.hostname
req.raw.protocol = req.protocol
req.raw.ip = req.ip
req.raw.ips = req.ips
req.raw.log = req.log
req.raw.query = req.query
reply.raw.log = req.log
if (req.body !== undefined) req.raw.body = req.body
this[kMiddie].run(req.raw, reply.raw, next)
} else {
next()
}
}
function runMiddieWithPayload (req, reply, _payload, next) {
runMiddie.bind(this)(req, reply, next)
}
function onMiddieEnd (err, req, res, next) {
next(err)
}
function onRegister (instance) {
const middlewares = instance[kMiddlewares].slice()
instance[kMiddlewares] = []
instance[kMiddie] = Middie(onMiddieEnd)
instance[kMiddieHasMiddlewares] = false
instance.decorate('use', use)
for (const middleware of middlewares) {
instance.use(...middleware)
}
}
next()
}
module.exports = fp(fastifyMiddie, {
fastify: '5.x',
name: '@fastify/middie'
})
module.exports.default = fastifyMiddie
module.exports.fastifyMiddie = fastifyMiddie