-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
59 lines (48 loc) · 1.75 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
const configValidate = require('./src/config-validate')
const fp = require('fastify-plugin')
const proxy = route => async (request, reply) => {
try {
request.req.url = request.req.url.replace(route.prefix, route.prefixRewrite)
const shouldAbortProxy = await route.hooks.onRequest(request, reply)
if (!shouldAbortProxy) {
reply.from(route.target + request.req.url, Object.assign({}, route.hooks))
}
} catch (err) {
reply.send(err)
}
}
const plugin = (fastify, opts, next) => {
opts = Object.assign({
middlewares: [],
pathRegex: '/*'
}, opts)
configValidate(opts)
// registering global middlewares
opts.middlewares.forEach(middleware => {
fastify.use(middleware)
})
opts.routes.forEach(route => {
if (undefined === route.prefixRewrite) {
route.prefixRewrite = ''
}
// registering routes level middlewares
if (route.middlewares) {
route.middlewares.forEach(middleware => {
fastify.use(route.prefix, middleware)
})
}
// populating required NOOPS
route.hooks = route.hooks || {}
route.hooks.onRequest = route.hooks.onRequest || (async (req, reply) => { })
route.hooks.onResponse = route.hooks.onResponse || ((req, reply, res) => reply.send(res))
// populating pathRegex if missing
route.pathRegex = undefined === route.pathRegex ? opts.pathRegex : String(route.pathRegex)
// preparing bodyLimit
const bodyLimit = route.bodyLimit ? Number(route.bodyLimit) : 1048576
// registering route handler
const methods = route.methods || ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
fastify.route({ method: methods, bodyLimit, url: route.prefix + route.pathRegex, handler: proxy(route) })
})
next()
}
module.exports = fp(plugin)