Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created November 3, 2017 23:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkarpov15/b4a9cb225699b3bf852c3fa8ca2c56e2 to your computer and use it in GitHub Desktop.
Save vkarpov15/b4a9cb225699b3bf852c3fa8ca2c56e2 to your computer and use it in GitHub Desktop.
Conditionally Required Properties with Archetype
const Archetype = require('archetype');
const CustomerType = new Archetype({
roles: {
$type: ['string'],
$enum: ['CUSTOMER', 'ADMIN'],
$required: true,
$default: ['CUSTOMER']
},
email: {
$type: 'string',
$required: true
},
department: {
$type: 'string',
// If `$required` is a function, archetype executes it with the
// top-level object as the first param. If the function returns
// something truthy, the property will be `$required`.
$required: doc => doc.roles.includes('ADMIN')
}
}).compile('CustomerType');
// OK
new CustomerType({ email: 'val@karpov.io' });
new CustomerType({
roles: ['ADMIN'],
email: 'test@test',
department: 'Engineering'
});
// "Error: department: Path "department" is required"
// Archetype error strings are of the form
// '<property1>: <message1>, <property2>: <message2>, ...'
new CustomerType({
roles: ['ADMIN'],
email: 'test@test'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment