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

Get default value of a property of an object when the object is an array item

Open vaidkaran opened this issue 3 years ago • 5 comments

I am trying to get the default value of pathFilter via convict.default() Below is my configSchema

  masks: {
    format: 'Object',
    body: {
      doc: 'masks for body',
      format: 'Array',
      default: [],
      children: {
        pathFilter: {
          format: RegExp,
          doc: 'Filter for applying mask to certain paths',
          default: /.*/,
        },
      },
    },
  },

And the config looks like:

    masks: {
      body: [
        {
          pathFilter: /xyz/,
        },
      ],
    }

I tried doing config.default('masks.body.children.pathFilter') but that doesn't work. One problem that I see here is that we add and look for _cvtProperties under arrays too. Arrays seem to have children and not _cvtProperties. So the default function would resolve the path and look for body._cvtProperties but it won't exist.

Maybe we need to cater for arrays here

Please advise.

vaidkaran avatar Apr 20 '22 16:04 vaidkaran

+1

koerbcm avatar Apr 20 '22 16:04 koerbcm

@vaidkaran or anyone interested, could you create a failing test demonstrating the problem please? That would help!

madarche avatar Apr 20 '22 16:04 madarche

const convict = require('convict');

const schema = {
  masks: {
    format: 'Object',
    body: {
      doc: 'masks for body',
      format: 'Array',
      default: [],
      children: {
        pathFilter: {
          format: RegExp,
          doc: 'Filter for applying mask to certain paths',
          default: /.*/,
        },
      },
    },
  },
}


const config = convict(schema).load({
  masks: {
    body: [
      {
        pathFilter: /xyz/,
      },
    ],
  },
}).validate();

const defaultBody = config.default('masks.body') // returns [] which is fine
console.log('Default value of body: ', defaultBody);

const defaultPathFilter = config.default('masks.body.children.pathFilter') // doesn't work
// Error: cannot find configuration param 'masks._cvtProperties.body._cvtProperties.children._cvtProperties.pathFilter.default'

Does this help?

vaidkaran avatar Apr 20 '22 17:04 vaidkaran

Any update on this?

koerbcm avatar May 09 '22 14:05 koerbcm

+1

TzachiSh avatar Jan 08 '23 11:01 TzachiSh