Skip to content

Commit

Permalink
make getPluginName resilient against too low stackTraceLimit (#209)
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak authored Jan 10, 2023
1 parent d7c3866 commit cd72d10
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/getPluginName.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ const fileNamePattern = /(\w*(\.\w*)*)\..*/
module.exports = function getPluginName (fn) {
if (fn.name.length > 0) return fn.name

const stackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = 10
try {
throw new Error('anonymous function')
} catch (e) {
Error.stackTraceLimit = stackTraceLimit
return extractPluginName(e.stack)
}
}
Expand Down
23 changes: 23 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,29 @@ test('should set anonymous function name to file it was called from with a count
t.end()
})

test('should set function name if Error.stackTraceLimit is set to 0', t => {
const stackTraceLimit = Error.stackTraceLimit = 0

const fp = proxyquire('../plugin.js', { stubs: {} })

const fn = fp((fastify, opts, next) => {
next()
})

t.equal(fn[Symbol.for('plugin-meta')].name, 'test-auto-0')
t.equal(fn[Symbol.for('fastify.display-name')], 'test-auto-0')

const fn2 = fp((fastify, opts, next) => {
next()
})

t.equal(fn2[Symbol.for('plugin-meta')].name, 'test-auto-1')
t.equal(fn2[Symbol.for('fastify.display-name')], 'test-auto-1')

Error.stackTraceLimit = stackTraceLimit
t.end()
})

test('should set display-name to meta name', t => {
t.plan(2)

Expand Down

0 comments on commit cd72d10

Please sign in to comment.