-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (63 loc) · 2.41 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
'use strict'
const fp = require('fastify-plugin')
// See https://github.com/fastify/fastify-plugin/blob/4a11ccc90df16b196e3f4746a5321938a87283f2/plugin.js#L46
const kFastifyDisplayName = Symbol.for('fastify.display-name')
async function fastifyOverride (app, opts = {}) {
const { plugins = {}, decorators = {}, hooks = {} } = opts.override ?? {}
function overrideDecorate (instance, type) {
if (!decorators[type]) return
const original = instance[type]
app[type] = function override (name, fn, dependencies) {
const pluginFn = decorators[type][name] ?? fn
return original.call(this, name, pluginFn, dependencies)
}
}
function overrideRegister (instance) {
const original = instance.register
instance.register = function (fn, options) {
if (isPromiseLike(fn)) {
instance.log.debug('Promise like plugin function cannot be overridden.')
}
if (isBundledOrTypescriptPlugin(fn)) {
fn = fn.default
}
const plugin = (fn[kFastifyDisplayName] && plugins[fn[kFastifyDisplayName]]) ?? fn
return original.call(this, plugin, options)
}
}
function overrideAddHook (instance) {
const original = instance.addHook
instance.addHook = function (name, hook) {
const hookFn = hooks[name] ?? hook
original.call(this, name, hookFn)
}
}
// From https://github.com/fastify/avvio/blob/a153be8358ece6a1ed970d0bee2c28a8230175b9/lib/is-bundled-or-typescript-plugin.js#L13-L19
function isBundledOrTypescriptPlugin (maybeBundledOrTypescriptPlugin) {
return (
maybeBundledOrTypescriptPlugin !== null &&
typeof maybeBundledOrTypescriptPlugin === 'object' &&
typeof maybeBundledOrTypescriptPlugin.default === 'function'
)
}
// From https://github.com/fastify/avvio/blob/a153be8358ece6a1ed970d0bee2c28a8230175b9/lib/is-promise-like.js#L7-L13
function isPromiseLike (maybePromiseLike) {
return (
maybePromiseLike !== null &&
typeof maybePromiseLike === 'object' &&
typeof maybePromiseLike.then === 'function'
)
}
overrideDecorate(app, 'decorate')
overrideDecorate(app, 'decorateReply')
overrideDecorate(app, 'decorateReply')
overrideRegister(app)
overrideAddHook(app)
}
const plugin = fp(fastifyOverride, {
name: 'fastify-override',
fastify: '4.x'
})
module.exports = plugin
module.exports.default = plugin
module.exports.fastifyOverride = fastifyOverride