-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathindex.js
107 lines (92 loc) · 2.71 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
107
'use strict'
const fp = require('fastify-plugin')
const Express = require('express')
const kMiddlewares = Symbol('fastify-express-middlewares')
function fastifyExpress (fastify, options, next) {
const {
expressHook = 'onRequest',
createProxyHandler
} = options
fastify.decorate('use', use)
fastify[kMiddlewares] = []
fastify.decorate('express', Express())
fastify.express.disable('x-powered-by')
fastify
.addHook(expressHook, enhanceRequest)
.addHook(expressHook, runConnect)
.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.express.use(path)
} else {
this.express.use(path, fn)
}
return this
}
function enhanceRequest (req, reply, next) {
// Allow attaching custom Proxy handlers to Express req
if (typeof createProxyHandler === 'function') {
req.raw = new Proxy(req.raw, createProxyHandler(req))
}
const { url } = req.raw
req.raw.originalUrl = 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
reply.raw.send = function send (...args) {
// Restore req.raw.url to its original value https://github.com/fastify/fastify-express/issues/11
req.raw.url = url
return reply.send.apply(reply, args)
}
// backward compatibility for body-parser
if (req.body) {
req.raw.body = req.body
}
// backward compatibility for cookie-parser
if (req.cookies) {
req.raw.cookies = req.cookies
}
// Make it lazy as it does a bit of work
Object.defineProperty(req.raw, 'protocol', {
get () {
return req.protocol
}
})
next()
}
function runConnect (req, reply, next) {
if (this[kMiddlewares].length > 0) {
for (const [headerName, headerValue] of Object.entries(reply.getHeaders())) {
reply.raw.setHeader(headerName, headerValue)
}
this.express(req.raw, reply.raw, next)
} else {
next()
}
}
function onRegister (instance) {
const middlewares = instance[kMiddlewares].slice()
instance[kMiddlewares] = []
instance.decorate('express', Express())
instance.express.disable('x-powered-by')
instance.decorate('use', use)
for (const middleware of middlewares) {
instance.use(...middleware)
}
}
next()
}
module.exports = fp(fastifyExpress, {
fastify: '5.x',
name: '@fastify/express'
})
module.exports.default = fastifyExpress
module.exports.fastifyExpress = fastifyExpress