-
-
Save danneu/5df7ca7b9063c078ff7f0967edd1f6f0 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, { | |
// 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