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

How do I specify a schema for array items?

Open mojavelinux opened this issue 8 years ago • 3 comments

In my application, I want to allow multiple items to be specified for a property. A good example of this is a list of data sources.

{
  "sources": [
    {
      "type": "git",
      "url": "https://github.com/mozilla/node-convict.git"
    },
    {
      "type": "git",
      "url": "https://github.com/github/hub.git"
    }
  ]
}

How do I specify a schema for each item? The best I can do is specify that the sources key takes an Array.

const schema = {
  sources: {
    doc: "A collection of data sources.",
    format: Array,
    default: []
  }
}

Do I need to use a custom format?

mojavelinux avatar Jan 25 '18 01:01 mojavelinux

This seems like the sort of thing that should have an easy helper function, but as a workaround, you could define a custom format like this:

const sourceSchema = {
  type: {
    doc: "The source type",
    format: ["git", "hg", "svn"],
    default: null
  },
  url: {
    doc: "The source URL",
    format: "url",
    default: null
  }
}

convict.addFormat({
  name: 'source-array',
  validate: function(sources) {
    if (!Array.isArray(sources)) {
      throw new Error('must be of type Array');
    }

    for (source of sources) {
      convict(sourceSchema).load(source).validate();
    }
  }
});

const schema = {
  sources: {
    doc: "A collection of data sources.",
    format: 'source-array',
    default: [],
  }
};

callahad avatar Feb 06 '19 22:02 callahad

I made #296 to improve this usage : https://github.com/mozilla/node-convict/tree/master/packages/convict#custom-format-for-array-items with children key:

const schema = {
  sources: {
    doc: 'A collection of data sources.',
    format: 'source-array',
    default: [],

    children: {
      type: {
        doc: 'The source type',
        format: ['git', 'hg', 'svn'],
        default: null
      },
      url: {
        doc: 'The source URL',
        format: 'url',
        default: null
      }
    }
  }
};

A-312 avatar Jul 29 '19 08:07 A-312

Woohoo! Thank you for your contribution!

callahad avatar Jul 29 '19 15:07 callahad