Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I specify a schema for array items? #238

Open
mojavelinux opened this issue Jan 25, 2018 · 3 comments
Open

How do I specify a schema for array items? #238

mojavelinux opened this issue Jan 25, 2018 · 3 comments

Comments

@mojavelinux
Copy link
Contributor

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?

@callahad
Copy link
Contributor

callahad commented Feb 6, 2019

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: [],
  }
};

@A-312
Copy link
Contributor

A-312 commented Jul 29, 2019

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
      }
    }
  }
};

@callahad
Copy link
Contributor

Woohoo! Thank you for your contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants