Created
November 11, 2017 01:05
-
-
Save vkarpov15/dcf7c490c69e625764c0dc1453555524 to your computer and use it in GitHub Desktop.
Configuring Custom Validators for Individual Paths in Archetype
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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