forked from fastify/fastify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastify.js
670 lines (565 loc) · 17.9 KB
/
fastify.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
'use strict'
const FindMyWay = require('find-my-way')
const avvio = require('avvio')
const Ajv = require('ajv')
const http = require('http')
const https = require('https')
const Middie = require('middie')
const fastIterator = require('fast-iterator')
const lightMyRequest = require('light-my-request')
const abstractLogging = require('abstract-logging')
const Reply = require('./lib/reply')
const Request = require('./lib/request')
const supportedMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
const buildSchema = require('./lib/validation').build
const handleRequest = require('./lib/handleRequest')
const isValidLogger = require('./lib/validation').isValidLogger
const schemaCompiler = require('./lib/validation').schemaCompiler
const decorator = require('./lib/decorate')
const ContentTypeParser = require('./lib/ContentTypeParser')
const Hooks = require('./lib/hooks')
const loggerUtils = require('./lib/logger')
const pluginUtils = require('./lib/pluginUtils')
function build (options) {
options = options || {}
if (typeof options !== 'object') {
throw new TypeError('Options must be an object')
}
var log
if (isValidLogger(options.logger)) {
log = loggerUtils.createLogger({ logger: options.logger, serializers: loggerUtils.serializers })
} else if (!options.logger) {
log = Object.create(abstractLogging)
log.child = () => log
} else {
options.logger = typeof options.logger === 'object' ? options.logger : {}
options.logger.level = options.logger.level || 'info'
options.logger.serializers = options.logger.serializers || loggerUtils.serializers
log = loggerUtils.createLogger(options.logger)
}
const ajv = new Ajv(Object.assign({ coerceTypes: true }, options.ajv))
const router = FindMyWay({ defaultRoute: defaultRoute })
const map = new Map()
// logger utils
const customGenReqId = options.logger ? options.logger.genReqId : null
const genReqId = customGenReqId || loggerUtils.reqIdGenFactory()
const now = loggerUtils.now
const onResponseIterator = loggerUtils.onResponseIterator
const onResponseCallback = loggerUtils.onResponseCallback
const app = avvio(fastify, {
autostart: false
})
// Override to allow the plugin incapsulation
app.override = override
var listening = false
// true when Fastify is ready to go
var started = false
app.on('start', () => {
started = true
})
var server
if (options.https) {
if (options.http2) {
server = http2().createSecureServer(options.https, fastify)
} else {
server = https.createServer(options.https, fastify)
}
} else if (options.http2) {
server = http2().createServer(fastify)
} else {
server = http.createServer(fastify)
}
fastify.onClose((instance, done) => {
if (listening) {
instance.server.close(done)
} else {
done(null)
}
})
if (Number(process.versions.node[0]) >= 6) {
server.on('clientError', handleClientError)
}
// shorthand methods
fastify.delete = _delete
fastify.get = _get
fastify.head = _head
fastify.patch = _patch
fastify.post = _post
fastify.put = _put
fastify.options = _options
fastify.all = _all
// extended route
fastify.route = route
fastify._RoutePrefix = new RoutePrefix()
// expose logger instance
fastify.log = log
// hooks
fastify.addHook = addHook
fastify._hooks = new Hooks()
// custom parsers
fastify.addContentTypeParser = addContentTypeParser
fastify.hasContentTypeParser = hasContentTypeParser
fastify._contentTypeParser = new ContentTypeParser()
fastify.setSchemaCompiler = setSchemaCompiler
fastify._schemaCompiler = schemaCompiler.bind({ ajv: ajv })
// plugin
fastify.register = fastify.use
fastify.listen = listen
fastify.server = server
fastify[pluginUtils.registeredPlugins] = []
// extend server methods
fastify.decorate = decorator.add
fastify.hasDecorator = decorator.exist
fastify.decorateReply = decorator.decorateReply
fastify.decorateRequest = decorator.decorateRequest
fastify._Reply = Reply.buildReply(Reply)
fastify._Request = Request.buildRequest(Request)
// middleware support
fastify.use = use
fastify._middie = Middie(onRunMiddlewares)
fastify._middlewares = []
// exposes the routes map
fastify[Symbol.iterator] = iterator
// fake http injection (for testing purposes)
fastify.inject = inject
var fourOhFour = FindMyWay({ defaultRoute: fourOhFourFallBack })
fastify.setNotFoundHandler = setNotFoundHandler
setNotFoundHandler.call(fastify)
fastify.setErrorHandler = setErrorHandler
return fastify
function fastify (req, res) {
req.id = genReqId(req)
req.log = res.log = log.child({ reqId: req.id })
req.originalUrl = req.url
req.log.info({ req }, 'incoming request')
res._startTime = now()
res._context = null
res.on('finish', onResFinished)
res.on('error', onResFinished)
res.on('close', onConnectionClosed)
router.lookup(req, res)
}
function onConnectionClosed () {
this.log.error({
res: this,
responseTime: now() - this._startTime
}, 'client connection was terminated')
}
function onResFinished (err) {
this.removeListener('finish', onResFinished)
this.removeListener('error', onResFinished)
var ctx = this._context
if (ctx && ctx.onResponse !== null) {
// deferring this with setImmediate will
// slow us by 10%
ctx.onResponse(
onResponseIterator,
this,
onResponseCallback
)
} else {
onResponseCallback(err, this)
}
}
function listen (port, address, cb) {
/* Deal with listen (port, cb) */
if (typeof address === 'function') {
cb = address
address = undefined
}
if (cb === undefined) {
return new Promise((resolve, reject) => {
fastify.listen(port, address, err => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
const hasAddress = address !== undefined
fastify.ready(function (err) {
if (err) return cb(err)
if (listening) {
return cb(new Error('Fastify is already listening'))
}
server.on('error', wrap)
if (hasAddress) {
server.listen(port, address, wrap)
} else {
server.listen(port, wrap)
}
listening = true
})
function wrap (err) {
server.removeListener('error', wrap)
cb(err)
}
}
function startHooks (req, res, params, context) {
res._context = context
if (context.onRequest !== null) {
context.onRequest(
hookIterator,
new State(req, res, params, context),
middlewareCallback
)
} else {
middlewareCallback(null, new State(req, res, params, context))
}
}
function State (req, res, params, context) {
this.req = req
this.res = res
this.params = params
this.context = context
}
function hookIterator (fn, state, next) {
return fn(state.req, state.res, next)
}
function middlewareCallback (err, state) {
if (err) {
const req = state.req
const request = new state.context.Request(state.params, req, null, req.headers, req.log)
const reply = new state.context.Reply(state.res, state.context, request)
reply.send(err)
return
}
state.context._middie.run(state.req, state.res, state)
}
function onRunMiddlewares (err, req, res, state) {
if (err) {
const request = new state.context.Request(state.params, req, null, req.headers, req.log)
const reply = new state.context.Reply(res, state.context, request)
reply.send(err)
return
}
handleRequest(req, res, state.params, state.context)
}
function override (old, fn, opts) {
const shouldSkipOverride = pluginUtils.registerPlugin.call(old, fn)
if (shouldSkipOverride) {
return old
}
const middlewares = Object.assign([], old._middlewares)
const instance = Object.create(old)
instance._Reply = Reply.buildReply(instance._Reply)
instance._Request = Request.buildRequest(instance._Request)
instance._contentTypeParser = ContentTypeParser.buildContentTypeParser(instance._contentTypeParser)
instance._hooks = Hooks.buildHooks(instance._hooks)
instance._RoutePrefix = buildRoutePrefix(instance._RoutePrefix, opts)
instance._middlewares = []
instance._middie = Middie(onRunMiddlewares)
instance[pluginUtils.registeredPlugins] = Object.create(instance[pluginUtils.registeredPlugins])
if (opts.prefix) {
instance._404Context = null
}
for (var i = 0; i < middlewares.length; i++) {
instance.use.apply(instance, middlewares[i])
}
return instance
}
function RoutePrefix () {
this.prefix = ''
}
function buildRoutePrefix (r, opts) {
const _RoutePrefix = Object.create(opts)
const R = _RoutePrefix
R.prefix = r.prefix
if (typeof opts.prefix === 'string') {
if (opts.prefix[0] !== '/') {
opts.prefix = '/' + opts.prefix
}
R.prefix += opts.prefix
}
return R
}
// Shorthand methods
function _delete (url, opts, handler) {
return _route(this, 'DELETE', url, opts, handler)
}
function _get (url, opts, handler) {
return _route(this, 'GET', url, opts, handler)
}
function _head (url, opts, handler) {
return _route(this, 'HEAD', url, opts, handler)
}
function _patch (url, opts, handler) {
return _route(this, 'PATCH', url, opts, handler)
}
function _post (url, opts, handler) {
return _route(this, 'POST', url, opts, handler)
}
function _put (url, opts, handler) {
return _route(this, 'PUT', url, opts, handler)
}
function _options (url, opts, handler) {
return _route(this, 'OPTIONS', url, opts, handler)
}
function _all (url, opts, handler) {
return _route(this, supportedMethods, url, opts, handler)
}
function _route (_fastify, method, url, options, handler) {
if (!handler && typeof options === 'function') {
handler = options
options = {}
}
return _fastify.route({
method,
url,
handler,
schema: options.schema,
beforeHandler: options.beforeHandler,
config: options.config,
schemaCompiler: options.schemaCompiler
})
}
// Route management
function route (opts) {
const _fastify = this
if (Array.isArray(opts.method)) {
for (var i = 0; i < opts.method.length; i++) {
if (supportedMethods.indexOf(opts.method[i]) === -1) {
throw new Error(`${opts.method[i]} method is not supported!`)
}
}
} else {
if (supportedMethods.indexOf(opts.method) === -1) {
throw new Error(`${opts.method} method is not supported!`)
}
}
if (!opts.handler) {
throw new Error(`Missing handler function for ${opts.method}:${opts.url} route.`)
}
_fastify._RoutePrefix = _fastify._RoutePrefix
_fastify.after((notHandledErr, done) => {
const path = opts.url || opts.path
const prefix = _fastify._RoutePrefix.prefix
const url = prefix + (path === '/' && prefix.length > 0 ? '' : path)
const config = opts.config || {}
config.url = url
const context = new Context(
opts.schema,
opts.handler.bind(_fastify),
_fastify._Reply,
_fastify._Request,
_fastify._contentTypeParser,
config,
_fastify._errorHandler,
_fastify._middie,
_fastify
)
try {
buildSchema(context, opts.schemaCompiler || _fastify._schemaCompiler)
} catch (error) {
done(error)
return
}
const onRequest = _fastify._hooks.onRequest
const onResponse = _fastify._hooks.onResponse
const onSend = _fastify._hooks.onSend
const preHandler = _fastify._hooks.preHandler.concat(opts.beforeHandler || [])
context.onRequest = onRequest.length ? fastIterator(onRequest, _fastify) : null
context.onResponse = onResponse.length ? fastIterator(onResponse, _fastify) : null
context.onSend = onSend.length ? fastIterator(onSend, _fastify) : null
context.preHandler = preHandler.length ? fastIterator(preHandler, _fastify) : null
if (map.has(url)) {
if (map.get(url)[opts.method]) {
return done(new Error(`${opts.method} already set for ${url}`))
}
if (Array.isArray(opts.method)) {
for (i = 0; i < opts.method.length; i++) {
map.get(url)[opts.method[i]] = context
}
} else {
map.get(url)[opts.method] = context
}
router.on(opts.method, url, startHooks, context)
} else {
const node = {}
if (Array.isArray(opts.method)) {
for (i = 0; i < opts.method.length; i++) {
node[opts.method[i]] = context
}
} else {
node[opts.method] = context
}
map.set(url, node)
router.on(opts.method, url, startHooks, context)
}
done(notHandledErr)
})
// chainable api
return _fastify
}
function Context (schema, handler, Reply, Request, contentTypeParser, config, errorHandler, middie, fastify) {
this.schema = schema
this.handler = handler
this.Reply = Reply
this.Request = Request
this.contentTypeParser = contentTypeParser
this.onRequest = null
this.onSend = null
this.preHandler = null
this.onResponse = null
this.config = config
this.errorHandler = errorHandler
this._middie = middie
this._fastify = fastify
}
function iterator () {
var entries = map.entries()
var it = {}
it.next = function () {
var next = entries.next()
if (next.done) {
return {
value: null,
done: true
}
}
var value = {}
var methods = {}
value[next.value[0]] = methods
// out methods are saved Uppercase,
// so we lowercase them for a better usability
for (var method in next.value[1]) {
methods[method.toLowerCase()] = next.value[1][method]
}
return {
value: value,
done: false
}
}
return it
}
function inject (opts, cb) {
if (started) {
return lightMyRequest(this, opts, cb)
}
if (cb) {
this.ready(err => {
if (err) throw err
return lightMyRequest(this, opts, cb)
})
} else {
return new Promise((resolve, reject) => {
this.ready(err => {
if (err) return reject(err)
resolve()
})
}).then(() => lightMyRequest(this, opts))
}
}
function use (url, fn) {
if (typeof url === 'string') {
const prefix = this._RoutePrefix.prefix
url = prefix + (url === '/' && prefix.length > 0 ? '' : url)
}
this._middlewares.push([url, fn])
this._middie.use(url, fn)
return this
}
function addHook (name, fn) {
if (name === 'onClose') {
this.onClose(fn)
} else {
this._hooks.add(name, fn)
}
return this
}
function addContentTypeParser (contentType, fn) {
this._contentTypeParser.add(contentType, fn)
return this
}
function hasContentTypeParser (contentType, fn) {
return this._contentTypeParser.hasParser(contentType)
}
function handleClientError (e, socket) {
const body = JSON.stringify({
error: http.STATUS_CODES['400'],
message: 'Client Error',
statusCode: 400
})
log.error(e, 'client error')
socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: 'application/json'\r\n\r\n${body}`)
}
function defaultRoute (req, res) {
fourOhFour.lookup(req, res)
}
function basic404 (req, reply) {
reply.code(404).send(new Error('Not found'))
}
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
req.log.warn('the default handler for 404 did not catch this, this is likely a fastify bug, please report it')
req.log.warn(fourOhFour.prettyPrint())
const request = new Request(null, req, null, req.headers, req.log)
const reply = new Reply(res, { onSend: fastIterator([], null) }, request)
reply.code(404).send(new Error('Not found'))
}
function setNotFoundHandler (opts, handler) {
this.after((notHandledErr, done) => {
_setNotFoundHandler.call(this, opts, handler)
done(notHandledErr)
})
}
function _setNotFoundHandler (opts, handler) {
if (typeof opts === 'function') {
handler = opts
opts = undefined
}
opts = opts || {}
handler = handler ? handler.bind(this) : basic404
if (!this._404Context) {
const context = new Context(
opts.schema,
handler,
this._Reply,
this._Request,
this._contentTypeParser,
opts.config || {},
this._errorHandler,
this._middie,
null
)
const onRequest = this._hooks.onRequest
const preHandler = this._hooks.preHandler
const onSend = this._hooks.onSend
const onResponse = this._hooks.onResponse
context.onRequest = onRequest.length ? fastIterator(onRequest, this) : null
context.preHandler = preHandler.length ? fastIterator(preHandler, this) : null
context.onSend = onSend.length ? fastIterator(onSend, this) : null
context.onResponse = onResponse.length ? fastIterator(onResponse, this) : null
this._404Context = context
var prefix = this._RoutePrefix.prefix
var star = '/*'
fourOhFour.all(prefix + star, startHooks, context)
fourOhFour.all(prefix || '/', startHooks, context)
} else {
this._404Context.handler = handler
this._404Context.contentTypeParser = this._contentTypeParser
this._404Context.config = opts.config || {}
}
}
function setSchemaCompiler (schemaCompiler) {
this._schemaCompiler = schemaCompiler
return this
}
function setErrorHandler (func) {
this._errorHandler = func
return this
}
}
function http2 () {
try {
return require('http2')
} catch (err) {
console.error('http2 is available only from node >= 8.8.1')
}
}
module.exports = build