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

Providing a default of undefined prevents format from being checked #278

Open
molomby opened this issue Feb 5, 2019 · 3 comments · Fixed by A-312/node-blueconfig#1
Open

Comments

@molomby
Copy link

molomby commented Feb 5, 2019

The docs are clear that defaults must be supplied and, although the specifics could be improved (#254), not supplying a default value usually errors out.

However, if undefined is given for a default value and the environment variable is also undefined, the format function is never called. This results in bugs like this...

var convict = require("convict");

var config = convict({
  something: {
    format: (val) => {
        if (typeof val === 'undefined' || val === null || val === '') {
            throw new Error('must be a non-empty string');
        }
    },
    default: undefined,
    env: "SOMETHING",
  },
});

config.validate({ allowed: 'strict' });

// If the `SOMETHING` env var isn't set, this will return `undefined` rather than erroring
// The format() function is never called
config.get('something');

Tested on 4.4.1, see RunKit

@molomby
Copy link
Author

molomby commented Feb 5, 2019

If you hit this in your own usage, one workaround is to set a default of null instead of undefined.

@cappslock
Copy link

This is actually really useful for trying to implement optional config properties so... thanks!

@A-312
Copy link
Contributor

A-312 commented Jan 6, 2020

validate don't check property with default === undefined and value === undefined... Set another value for default. ;-)

5535379#diff-7763d1369911b91b757ba7ff51d734a2R65

Solution
var convict = require("convict");

var config = convict({
  something: {
    format: function (val, schema) {
        console.log(arguments);
        if (schema.env && val === '') {
          throw new Error(`env[${schema.env}] is not set !`)
        }
        if (typeof val === 'undefined' || val === null || val === '') {
            throw new Error('must be a non-empty string');
        }
    },
    default: '',
    env: "SOMETHING",
  },
});

config.validate({ allowed: 'strict' });

// If the `SOMETHING` env var isn't set, this will return `undefined` rather than erroring
// The format() function is never called
console.log(config.get('something'));

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants