forked from fastify/fastify-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (67 loc) · 1.92 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
'use strict'
const fp = require('fastify-plugin')
const symbols = require('fastify/lib/symbols')
const Express = require('express')
const kMiddlewares = Symbol('fastify-express-middlewares')
const kExpress = Symbol('fastify-express-instance')
function expressPlugin (fastify, options, next) {
// TODO: we should use decorate, but `use` is already
// a public API of Fastify. In Fastify v3 it will be deprecated,
// so we will able to use `decorate`
fastify.use = use
fastify[kMiddlewares] = []
fastify[kExpress] = Express()
fastify
.addHook('onRequest', enhanceRequest)
.addHook('onRequest', runConnect)
.addHook('onSend', runOnSend)
.addHook('onRegister', onRegister)
function use (path, fn) {
if (typeof path === 'string') {
const prefix = this[symbols.kRoutePrefix]
path = prefix + (path === '/' && prefix.length > 0 ? '' : path)
}
this[kMiddlewares].push([path, fn])
if (fn == null) {
this[kExpress].use(path)
} else {
this[kExpress].use(path, fn)
}
return this
}
function enhanceRequest (req, reply, next) {
req.raw.originalUrl = req.raw.url
req.raw.id = req.id
req.raw.hostname = req.hostname
req.raw.ip = req.ip
req.raw.ips = req.ips
req.raw.log = req.log
reply.raw.log = req.log
next()
}
function runConnect (req, reply, next) {
if (this[kMiddlewares].length > 0) {
this[kExpress](req.raw, reply.raw, next)
} else {
next()
}
}
function runOnSend (req, reply, payload, next) {
reply.raw.removeHeader('x-powered-by')
next()
}
function onRegister (instance) {
const middlewares = instance[kMiddlewares].slice()
instance[kMiddlewares] = []
instance[kExpress] = Express()
instance.use = use
for (const middleware of middlewares) {
instance.use(...middleware)
}
}
next()
}
module.exports = fp(expressPlugin, {
fastify: '>=3.0.0',
name: 'fastify-express'
})