Skip to content

Commit

Permalink
fix: Better plugin name detection for FSTWRN002 (#5209)
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <hello@matteocollina.com>
  • Loading branch information
mcollina committed Dec 14, 2023
1 parent 256fb2c commit e495eaa
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
6 changes: 3 additions & 3 deletions lib/pluginUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,14 @@ function registerPluginName (fn) {
return name
}

function checkPluginHealthiness (fn, pluginName = 'anonymous') {
function checkPluginHealthiness (fn, pluginName) {
if (fn.constructor.name === 'AsyncFunction' && fn.length === 3) {
FSTWRN002(pluginName)
FSTWRN002(pluginName || 'anonymous')
}
}

function registerPlugin (fn) {
const pluginName = registerPluginName.call(this, fn)
const pluginName = registerPluginName.call(this, fn) || getPluginName(fn)
checkPluginHealthiness.call(this, fn, pluginName)
checkVersion.call(this, fn)
checkDecorators.call(this, fn)
Expand Down
31 changes: 25 additions & 6 deletions test/plugin.4.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,29 +416,48 @@ test('hasPlugin returns true when using encapsulation', async t => {
})

test('registering plugins with mixed style should return a warning', async t => {
t.plan(4)
t.plan(12)

const pluginNames = ['error-plugin', 'anonymous', 'anotherPlugin', 'anotherPluginNamed']

const oldWarnings = process.listeners('warning')
process.removeAllListeners('warning')
process.on('warning', onWarning)
function onWarning (warning) {
t.match(warning.message, new RegExp(`.*${pluginNames.shift()} plugin being registered mixes async and callback styles.*`))
t.equal(warning.name, 'FastifyWarning')
t.equal(warning.code, 'FSTWRN002')
}
t.teardown(() => {
process.removeListener('warning', onWarning)
for (const warning of oldWarnings) {
process.on('warning', warning)
}
})

const fastify = Fastify()

const anonymousPlugin = async (app, opts, done) => {
done()
}

const pluginName = 'error-plugin'
const errorPlugin = async (app, opts, done) => {
done()
}

const namedPlugin = fp(errorPlugin, { name: pluginName })

async function anotherPlugin (app, opts, done) {
done()
}

const anotherPluginNamed = async function (app, opts, done) {
done()
}

fastify.register(namedPlugin)
fastify.register(anonymousPlugin)
fastify.register(async (app, opts, done) => {
done()
})
fastify.register(anotherPlugin)
fastify.register(anotherPluginNamed)

await fastify.ready()
})

0 comments on commit e495eaa

Please sign in to comment.