Skip to content

Commit

Permalink
fix: config deep merge
Browse files Browse the repository at this point in the history
  • Loading branch information
Eomm committed Nov 20, 2022
1 parent e844f4d commit 9ed8f05
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 5 deletions.
19 changes: 19 additions & 0 deletions examples/plugin-with-logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict'

module.exports = function (fastify, options, next) {
fastify.get('/', function (req, reply) {
reply.send({ hello: 'world' })
})
next()
}

module.exports.options = {
logger: {
redact: {
censor: '***',
paths: [
'foo',
]
},
}
}
16 changes: 11 additions & 5 deletions start.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
require('dotenv').config()
const isDocker = require('is-docker')
const closeWithGrace = require('close-with-grace')
const deepmerge = require('@fastify/deepmerge')({
cloneProtoObject(obj){ return obj }
})

const listenAddressDocker = '0.0.0.0'
const watch = require('./lib/watch')
const parseArgs = require('./args')
Expand Down Expand Up @@ -99,7 +103,7 @@ async function runFastify (args, additionalOptions, serverOptions) {
const defaultLogger = {
level: opts.logLevel
}
const options = {
let options = {
logger: logger || defaultLogger,

pluginTimeout: opts.pluginTimeout
Expand Down Expand Up @@ -127,12 +131,14 @@ async function runFastify (args, additionalOptions, serverOptions) {
}

if (serverOptions) {
Object.assign(options, serverOptions)
options = deepmerge(options, serverOptions)
}

if (opts.options && file.options) {
options = deepmerge(options, file.options)
}

const fastify = Fastify(
opts.options ? Object.assign(options, file.options) : options
)
const fastify = Fastify(options)

if (opts.prefix) {
opts.pluginOptions.prefix = opts.prefix
Expand Down
26 changes: 26 additions & 0 deletions test/helper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,29 @@ test('should start fastify with custom logger configuration', async t => {
t.same(lines.length, 1)
t.same(app.log.level, 'warn')
})

test('should merge the CLI and FILE configs', async t => {
const argv = ['./examples/plugin-with-logger.js', '--options']

const lines = []
const dest = new stream.Writable({
write: function (chunk, enc, cb) {
lines.push(JSON.parse(chunk))
cb()
}
})

const app = await helper.listen(argv, {}, {
logger: {
level: 'warn',
stream: dest
}
})
t.teardown(() => app.close())
app.log.info('test')
t.same(lines.length, 0)
app.log.warn({ foo: 'test' })
t.same(app.log.level, 'warn')
t.same(lines.length, 1)
t.same(lines[0].foo, '***')
})

0 comments on commit 9ed8f05

Please sign in to comment.