node-convict icon indicating copy to clipboard operation
node-convict copied to clipboard

Improvement: allow partial validation to check values used before config is ready

Open Xerkus opened this issue 9 years ago • 1 comments

A way to do partial validation is needed for the cases where value from incomplete config is used to finish setting it up. With sample code below node index.js --config config.js will fail (hopefully) on loadFile()

const convict = require('convict');
const path = require('path');

convict.addFormat({
    name: 'configfile',
    validate: (val) => {
        // Some sample checks 
        if (typeof val !== 'string' || ! val.endsWith('.json')) {
            throw new TypeError('Path must be a string pointing to json file');
        }
    },
    coerce: (val) => {
        return path.resolve(val);
    },
});

const conf = convict({
    config: {
        doc: 'Configuration file to use',
        format: 'configfile',
        default: path.resolve(__dirname, 'config.json'),
        arg: 'config',
    },
});

// fs, json5 or some other error is thrown here
conf.loadFile(conf.get('config'));

And with partial validation we can be sure values are good:

// validate 'config' only, validation error will be thrown here and loadFile will never be reached
conf.validate({}, ['config']);
conf.loadFile(conf.get('config'));

This case is fairly safe, but it gets more important if, for example, that value is used to fetch config from external storage

Xerkus avatar Sep 20 '16 02:09 Xerkus

Solution : Should be to run 2 instances of convict.

A-312 avatar Dec 07 '19 09:12 A-312