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

Dynamic default values

Open ncjones opened this issue 7 years ago • 5 comments

I'd like to be able to define config defaults in terms of other configs. For example, the schema could allow a variable expansion syntax like the following:

  const schema = { 
    env: {
      format: '*',
      default: 'test'
    },
    baseUrl: { 
      format: 'url',
      default: 'http://${env}.my-domain/'
    },
  }

In the above case the call to config.get('baseUrl'), with no other configs defined, would return 'http://test.my-domain/'.

ncjones avatar Jan 22 '18 03:01 ncjones

Would this be better implemented with a hook function instead of string interpolation?

EDIT: there's nothing stopping you from using native JS variables and string interp.

bugeats avatar Aug 23 '18 16:08 bugeats

I would also like to use some computed default values, based on real values of other settings. I have put some workaround, but it would be nice to have the capacity to put a function instead of a static value in the defaults.

spikying avatar Apr 06 '19 20:04 spikying

Hi guys... any update on this? @ncjones I also have the same requirements, how did manage to get around yours?

sohailalam2 avatar Apr 09 '19 07:04 sohailalam2

I only use my environment name for dynamic defaults so I just have a special environment variable for this:

// src/config/schema.js
const env = process.env['ENV'] || 'local'
module.exports = {
  gcpProject: {
    format: String,
    default: `my-app-${env}`,
    env: 'GCP_PROJECT',
  }
}

ncjones avatar Apr 09 '19 17:04 ncjones

Actually you can with : #110 but :

since code too complicated already and only works in limited cases

In my opinion, the change should be done only after convict thing, not in live during the loading. This will add too many loop, we should check for each env change.

It is very simple to make a recursive function at the end. But if you really don't want to do with your own function. PR an compile function (https://github.com/mozilla/node-convict/pull/110#issuecomment-562820329) :

convict.addCompiler('value', (v) => { /* ... */ })
config.load({
  gcpProject: {
    format: String,
    default: `my-app-${env}`,
    env: 'GCP_PROJECT',
  }
})
config.compile()
config.validate()

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