Simple `convict.load()` example

node v10.24.1
version: 1.0.0
endpointsharetweet
First, of course, we need a convict itself:
let convict = require("convict")
Then, we can define our schema:
let configSchema = { launchTime: { doc: 'Time Convict was loaded', format: 'string', env: 'TIME' }, port: { doc: 'The port to bind.', format: 'int', default: 8080, env: 'PORT', providerPath: '/port' } };
Of course, `providerPath` isn't actually part of the `convict` schema! But it doesn't mind. This can be used for further processing in your `load()` function.
Now, we need to define our loader function. I usually call this a `provider`. It needs to return a JavaScript object that matches the keys in your `configSchema`, but the values can be dynamically generated. While you can pass this function the full `convict` object, I find it easier to deal with the schema itself:
let provider = function(configSchema){ // simulating an outside data source let customKeyValueStore = { '/port': 8000 } let obj = {}; obj.launchTime = Date.now(); obj.port = customKeyValueStore[configSchema.port.providerPath] return obj; }
This function will return an object like this:
console.log(provider(configSchema))
Which we can then, finally, pass into `convict`:
let conf = convict(configSchema).load(provider(configSchema));
I usually statically return the parsed `convict` config using a call to getPropeties() and import it where I need it:
module.exports = conf.getProperties() // in another module... // let config = require('./config') // console.log(config)
Loading…

1 comment

  • posted 5 years ago by zaverden
    Nice idea with `provider`. I have several questions about your `configSchema` 1. Your `launchTime` parameter has `format: string` but you put a number there. May be it is better to change to `timestamp` to make it less confusing for newcomers 2. `launchTime` does not have `default` field - because of this `convict` processes this field wrong. You can see it at line 30 if you check `conf._schema.properties.launchTime` value - it does not contain schema definition

sign in to comment