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