MCPcopy Create free account
hub / github.com/fastify/fastify / addHook

Function addHook

fastify.js:572–617  ·  view source on GitHub ↗
(name, fn)

Source from the content-addressed store, hash-verified

570
571 // wrapper that we expose to the user for hooks handling
572 function addHook (name, fn) {
573 throwIfAlreadyStarted('Cannot call "addHook"!')
574
575 if (fn == null) {
576 throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn)
577 }
578
579 if (name === 'onSend' || name === 'preSerialization' || name === 'onError' || name === 'preParsing') {
580 if (fn.constructor.name === 'AsyncFunction' && fn.length === 4) {
581 throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
582 }
583 } else if (name === 'onReady' || name === 'onListen') {
584 if (fn.constructor.name === 'AsyncFunction' && fn.length !== 0) {
585 throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
586 }
587 } else if (name === 'onRequestAbort') {
588 if (fn.constructor.name === 'AsyncFunction' && fn.length !== 1) {
589 throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
590 }
591 } else {
592 if (fn.constructor.name === 'AsyncFunction' && fn.length === 3) {
593 throw new errorCodes.FST_ERR_HOOK_INVALID_ASYNC_HANDLER()
594 }
595 }
596
597 if (name === 'onClose') {
598 this.onClose(fn.bind(this))
599 } else if (name === 'onReady' || name === 'onListen' || name === 'onRoute') {
600 this[kHooks].add(name, fn)
601 } else {
602 this.after((err, done) => {
603 try {
604 _addHook.call(this, name, fn)
605 done(err)
606 } catch (err) {
607 done(err)
608 }
609 })
610 }
611 return this
612
613 function _addHook (name, fn) {
614 this[kHooks].add(name, fn)
615 this[kChildren].forEach(child => _addHook.call(child, name, fn))
616 }
617 }
618
619 // wrapper that we expose to the user for schemas handling
620 function addSchema (schema) {

Callers

nothing calls this directly

Calls 4

throwIfAlreadyStartedFunction · 0.85
addMethod · 0.80
afterMethod · 0.80
doneFunction · 0.50

Tested by

no test coverage detected