Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve index.js #171

Merged
merged 1 commit into from
Dec 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,27 @@

const fp = require('fastify-plugin')
const verifyBearerAuthFactory = require('./lib/verify-bearer-auth-factory')
const { FST_BEARER_AUTH_INVALID_LOG_LEVEL } = require('./lib/errors')

function fastifyBearerAuth (fastify, options, done) {
const defaultLogLevel = 'error'
options = Object.assign({ addHook: true, verifyErrorLogLevel: defaultLogLevel }, options)
options = Object.assign({ addHook: true, verifyErrorLogLevel: 'error' }, options)

if (!Object.prototype.hasOwnProperty.call(fastify.log, 'error') ||
(typeof fastify.log.error) !== 'function') options.verifyErrorLogLevel = null
if (options.verifyErrorLogLevel != null &&
(typeof options.verifyErrorLogLevel !== 'string' ||
!Object.prototype.hasOwnProperty.call(fastify.log, options.verifyErrorLogLevel) ||
(typeof fastify.log[options.verifyErrorLogLevel]) !== 'function'
)) {
const invalidLogLevelError = Error(`fastify.log does not have level '${options.verifyErrorLogLevel}'`)
done(invalidLogLevelError)
if (
Object.prototype.hasOwnProperty.call(fastify.log, 'error') === false ||
typeof fastify.log.error !== 'function'
) {
options.verifyErrorLogLevel = null
}

if (
options.verifyErrorLogLevel != null &&
(
typeof options.verifyErrorLogLevel !== 'string' ||
Object.prototype.hasOwnProperty.call(fastify.log, options.verifyErrorLogLevel) === false ||
typeof fastify.log[options.verifyErrorLogLevel] !== 'function'
)
) {
done(new FST_BEARER_AUTH_INVALID_LOG_LEVEL(options.verifyErrorLogLevel))
}

if (options.addHook === true) {
Expand Down
9 changes: 9 additions & 0 deletions lib/errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict'

const createError = require('@fastify/error')

const FST_BEARER_AUTH_INVALID_LOG_LEVEL = createError('FST_BEARER_AUTH_INVALID_LOG_LEVEL', 'fastify.log does not have level \'%s\'')

module.exports = {
FST_BEARER_AUTH_INVALID_LOG_LEVEL
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"tsd": "^0.30.0"
},
"dependencies": {
"@fastify/error": "^3.4.1",
"fastify-plugin": "^4.0.0"
},
"pre-commit": [
Expand Down
Loading