How do I specify a schema for array items?
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?
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: [],
}
};
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
}
}
}
};
Woohoo! Thank you for your contribution!