Convict doesn't persist date / other custom objects
irgijs opened this issue · comments
I ran into an issue where convict doesn't persist configuration data if you attempt to set a custom-defined configuration object such as a date. Instead of returning the value that has been set, the default value is returned - even though that is a date as well.
Code to reproduce:
const convict = require('convict');
convict.addFormat('date', value => assertValidDate(value), date => new Date(date));
/**
* Supporting function used to verify whether a string is formatted as a valid date.
*
* @param {string} date - The string which should be checked.
* @throws {Error} if assertion fails.
*/
function assertValidDate(date) {
// Date constructor does not throw an error if an invalid date is provided. valueOf() returns NaN when a date is invalid.
if (Number.isNaN(date.valueOf())) {
throw new Error('Provided value is not a valid date');
}
}
// configuration schema
const configurationSchema = {
installDate: {
doc: 'Date on which ',
format: 'date',
default: new Date('8900-12-31Z'),
},
};
// config that is set
const configFileData = {
installDate: new Date('2021-01-01Z'),
}
const config = convict(configurationSchema).load(configFileData);
const installDate = config.get('installDate');
// output: 8900-12-31T00:00:00.000Z
// expected: 2021-01-01T00:00:00.000Z
console.log(installDate.toISOString());
It seems that this bug is caused by the function overlay
- The first time the if statement in this function is called it evaluates to
false
, so the overlay is function is called again. - The second time the overlay function is called, the parameter
from
=new Date('2021-01-01Z')
andto
isnew Date('8900-12-31Z')
Object.keys(from)
returnsarray[0]
, therefore the default parameter is never overwritten.- The config still contains the default value instead of the value I attempted to set. No warning is generated.
Expected result: The config value I tried to set is persisted.