Skip to content

How to set a default after the fact #291

@ronkorving

Description

@ronkorving

I have a project where I put a lot of overridable values into convinct, and a common use-case I encounter is that I want to set default values late.

Example:

schema.yml:

organization:
  name:
    doc: Name of the organization
    format: String
    default: null
    arg: organization-name
domainName:
  doc: The domain name to be registered for the website
  format: String
  default: null
  arg: domain-name

I would like the domain name to default to ${organization.name}.awesomewebsites.com. The organization-name is not optional; it has to be provided. But the domain-name can be custom, but has a very obvious default based on the organization-name.

How can I achieve this with convict? Assuming this is currently impossible, I can see 3 theoretical solutions:

Via templates

schema.yml:

organization:
  name:
    doc: Name of the organization
    format: String
    default: null
    arg: organization-name
domainName:
  doc: The domain name to be registered for the website
  format: String
  default: '${organization.name}.awesomewebsites.com'   // convict will resolve this late, when the default is first needed
  arg: domain-name

Benefit:

  • You could still print the default in --help output.

Via a default-function

schema.js:

module.exports = {
  organization: {
    name: {
      doc: 'Name of the organization',
      format: String,
      default: null,
      arg: 'organization-name'
    }
  },
  domainName: {
    doc: 'The domain name to be registered for the website',
    format: String,
    default: (config) => {
      return config.get('organization.name') + '.awesomewebsites.com';
    },
    arg: 'domain-name'
  }
};

Benefit:

  • Most powerful solution wrt. the actual value (allowing conditional logic).
  • Is in the spirit of the "Usage" example in the readme (using env/NODE_ENV).

Via API

const config = convict(mySchema);
config.loadFile('config.yml');
config.setDefault('domainName', config.get('organization.name') + '.awesomewebsites.com');

Drawback:

  • Default value no longer exists in the same file as the schema.

Benefit:

  • Allows schema to be JSON or YAML (but format and coerce already defy that anyway).

I would love to hear what y'all think about feasibility and if there's any preference wrt. the solutions. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions