-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
fourOhFour.js
173 lines (147 loc) · 4.99 KB
/
fourOhFour.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
'use strict'
const FindMyWay = require('find-my-way')
const Reply = require('./reply')
const Request = require('./request')
const Context = require('./context')
const {
kRoutePrefix,
kCanSetNotFoundHandler,
kFourOhFourLevelInstance,
kReply,
kRequest,
kContentTypeParser,
kBodyLimit,
kLogLevel,
kFourOhFourContext,
kHooks,
kErrorHandler
} = require('./symbols.js')
const { lifecycleHooks } = require('./hooks')
const fourOhFourContext = {
config: {
},
onSend: [],
onError: []
}
/**
* Each fastify instance have a:
* kFourOhFourLevelInstance: point to a fastify instance that has the 404 handler setted
* kCanSetNotFoundHandler: bool to track if the 404 handler has already been set
* kFourOhFour: the singleton instance of this 404 module
* kFourOhFourContext: the context in the reply object where the handler will be executed
*/
function fourOhFour (options) {
const { logger, genReqId } = options
// 404 router, used for handling encapsulated 404 handlers
const router = FindMyWay({ defaultRoute: fourOhFourFallBack })
return { router, setNotFoundHandler, setContext, arrange404 }
function arrange404 (instance) {
// Change the pointer of the fastify instance to itself, so register + prefix can add new 404 handler
instance[kFourOhFourLevelInstance] = instance
instance[kCanSetNotFoundHandler] = true
}
function basic404 (request, reply) {
const { url, method } = request.raw
const message = `Route ${method}:${url} not found`
request.log.info(message)
reply.code(404).send({
message,
error: 'Not Found',
statusCode: 404
})
}
function setContext (instance, context) {
const _404Context = Object.assign({}, instance[kFourOhFourContext])
_404Context.onSend = context.onSend
context[kFourOhFourContext] = _404Context
}
function setNotFoundHandler (opts, handler, avvio, routeHandler) {
// First initialization of the fastify root instance
if (this[kCanSetNotFoundHandler] === undefined) {
this[kCanSetNotFoundHandler] = true
}
if (this[kFourOhFourContext] === undefined) {
this[kFourOhFourContext] = null
}
const _fastify = this
const prefix = this[kRoutePrefix] || '/'
if (this[kCanSetNotFoundHandler] === false) {
throw new Error(`Not found handler already set for Fastify instance with prefix: '${prefix}'`)
}
if (typeof opts === 'object') {
if (opts.preHandler) {
if (Array.isArray(opts.preHandler)) {
opts.preHandler = opts.preHandler.map(hook => hook.bind(_fastify))
} else {
opts.preHandler = opts.preHandler.bind(_fastify)
}
}
if (opts.preValidation) {
if (Array.isArray(opts.preValidation)) {
opts.preValidation = opts.preValidation.map(hook => hook.bind(_fastify))
} else {
opts.preValidation = opts.preValidation.bind(_fastify)
}
}
}
if (typeof opts === 'function') {
handler = opts
opts = undefined
}
opts = opts || {}
if (handler) {
this[kFourOhFourLevelInstance][kCanSetNotFoundHandler] = false
handler = handler.bind(this)
} else {
handler = basic404
}
this.after((notHandledErr, done) => {
_setNotFoundHandler.call(this, prefix, opts, handler, avvio, routeHandler)
done(notHandledErr)
})
}
function _setNotFoundHandler (prefix, opts, handler, avvio, routeHandler) {
const context = new Context(
opts.schema,
handler,
this[kReply],
this[kRequest],
this[kContentTypeParser],
opts.config || {},
this[kErrorHandler],
this[kBodyLimit],
this[kLogLevel]
)
avvio.once('preReady', () => {
const context = this[kFourOhFourContext]
for (const hook of lifecycleHooks) {
const toSet = this[kHooks][hook]
.concat(opts[hook] || [])
.map(h => h.bind(this))
context[hook] = toSet.length ? toSet : null
}
})
if (this[kFourOhFourContext] !== null && prefix === '/') {
Object.assign(this[kFourOhFourContext], context) // Replace the default 404 handler
return
}
this[kFourOhFourLevelInstance][kFourOhFourContext] = context
router.all(prefix + (prefix.endsWith('/') ? '*' : '/*'), routeHandler, context)
router.all(prefix, routeHandler, context)
}
function fourOhFourFallBack (req, res) {
// if this happen, we have a very bad bug
// we might want to do some hard debugging
// here, let's print out as much info as
// we can
const id = genReqId(req)
const childLogger = logger.child({ reqId: id })
childLogger.info({ req }, 'incoming request')
const request = new Request(id, null, req, null, childLogger, fourOhFourContext)
const reply = new Reply(res, request, childLogger)
request.log.warn('the default handler for 404 did not catch this, this is likely a fastify bug, please report it')
request.log.warn(router.prettyPrint())
reply.code(404).send(new Error('Not Found'))
}
}
module.exports = fourOhFour