parse
Validates data and returns it if valid, or throws ValidationError. Handy on the server, where an invalid request should stop processing right away.
Signature
ts
function parse<S extends Schema>(schema: S, value: unknown, options?: Options): Infer<S>Parameters
| Parameter | Type | Description |
|---|---|---|
schema | Schema | The schema to validate against |
value | unknown | Any data |
options | Options | { all?: boolean } — as in validate |
Returns
Cleaned, typed data — the same as result.data of validate.
Throws
ValidationError— if the data is invalid. It containserrorsandissues.Error— if the schema containscheckAsync. UseparseAsync.
Examples
Express
ts
import { parse, ValidationError } from 'tinyval';
app.post('/users', (req, res) => {
try {
const user = parse(CreateUser, req.body);
// user is validated and typed
} catch (e) {
if (e instanceof ValidationError) return res.status(422).json({ errors: e.errors });
throw e;
}
});Environment variables
ts
const env = parse(
object({
PORT: optional(coerce.number(), 3000),
DATABASE_URL: string(),
DEBUG: optional(coerce.boolean(), false),
}),
process.env,
);
// without DATABASE_URL the app fails on startup with a clear errorSee also
- ValidationError
- parseAsync
- validate — without exceptions