-
-
Save danneu/de648714362c6268aeeb7024508a7fa9 to your computer and use it in GitHub Desktop.
This file contains 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
import { v, validate } from '.' | |
async function run() { | |
const body = { | |
uname: ' foo ', | |
pass1: 'secret', | |
pass2: 'secret', | |
nums: [1, 2, 3], | |
users: [{ uname: 'foo' }, { uname: 'bar' }], | |
a: { b: 42 }, | |
} | |
const result = await validate(body, { | |
// optional value short-circuits if the key is missing | |
maybe: [v.optional(), v.isString()], | |
// reach into objects | |
a: { | |
b: [v.isInteger()], | |
}, | |
// verify each object in array and then transform the array | |
users: [ | |
v.arrayOf({ | |
uname: [v.isString()], | |
}), | |
v.map(xs => xs.map(user => user.uname)), | |
], | |
// verify each number in array and then sum the numbers | |
nums: [ | |
v.arrayOf([v.isInteger()]), | |
v.map(xs => xs.reduce((acc, n) => acc + n, 0)), | |
], | |
uname: [v.tip('test'), v.map(s => s.trim())], | |
pass1: [v.isString()], | |
}) | |
// check against a previous validation result | |
await validate(body, { | |
pass2: [v.isString(), v.eq(result.pass1)], | |
}) | |
// validated + transformed result is: | |
// | |
// { a: { b: 42 }, | |
// users: ['foo', 'bar'], | |
// nums: 6, | |
// uname: 'foo', | |
// pass1: 'secret' } | |
return result | |
} | |
run().then(console.log, console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment