loggers-factory
Version:
Javascript package that makes the use of loggers a breath.
79 lines (70 loc) • 2.24 kB
JavaScript
const get_default_console_format = require("./get_default_console_format.js");
const get_default_log_format = require("./get_default_log_format.js");
/**
* Deep merge the given params with the default ones.
* @see https://stackoverflow.com/a/34749873
*/
function merge_parameters(params) {
const default_params = requireUncached("./default_params.js");
// First, we update the format in case a source was given
// because the mergeDeep function can't do that.
if ("source" in params) {
default_params.transport.console.format = get_default_console_format(
params["source"]
);
for (const log_type of ["combined", "errors"]) {
default_params.transport.logs[log_type].format = get_default_log_format(
params["source"]
);
}
}
// We also update the logs paths if a path was given.
// In params have both a path for all the logs and a
// special path for one of the logs, there's no problem.
if ("logs_path" in params) {
for (const log_type of ["combined", "errors"]) {
default_params.transport.logs[log_type].logs_path = params["logs_path"];
}
}
return mergeDeep(default_params, params);
}
/**
* We require the default params at each function call
* in order to always have the actual default parameters:
* If we require before the function, the default merge_parameters
* won't be the same after a function call.
* @see https://stackoverflow.com/a/16060619
*/
function requireUncached(module_path) {
delete require.cache[require.resolve(module_path)];
return require(module_path);
}
/**
* Simple object check.
* @param item
* @returns {Boolean}
*/
function isObject(item) {
return item && typeof item === "object" && !Array.isArray(item);
}
/**
* Deep merge two objects.
* @param target
* @param ...sources
*/
function mergeDeep(target, ...sources) {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return mergeDeep(target, ...sources);
}
module.exports = merge_parameters;