Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created November 11, 2017 01:05
Show Gist options
  • Save vkarpov15/dcf7c490c69e625764c0dc1453555524 to your computer and use it in GitHub Desktop.
Save vkarpov15/dcf7c490c69e625764c0dc1453555524 to your computer and use it in GitHub Desktop.
Configuring Custom Validators for Individual Paths in Archetype
const Archetype = require('archetype');
const assert = require('assert');
// The 2nd param to the `$validate` function is the schema path,
// so `{ $type: 'number', ... }`. Can use that to configure
// validators from your schema path, like writing your own
// min/max validator
const minMax = (v, path) => {
const { $min, $max } = path;
assert.ok($min == null || v >= $min, `${v} < ${$min}`);
assert.ok($max == null || v <= $max, `${v} > ${$max}`);
};
const TweetType = new Archetype({
length: {
$type: 'number',
// minMax gets access to `$min` and `$max` below
$validate: minMax,
$min: 0,
$max: 140
},
retweets: {
$type: 'number',
// minMax behaves differently because different `$min` and `$max`
$validate: minMax,
$min: 100
}
}).compile('TweetType');
// OK
new TweetType({ length: 127, retweets: 100 });
try {
new TweetType({ length: 151 });
} catch (error) {
// Error: length: 151 > 140
console.error(error.message);
}
try {
new TweetType({ retweets: 99 });
} catch (error) {
// Error: retweets: 99 < 100
console.error(error.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment