0.0.6 • Published 1 year ago
@typesafe-validator/core v0.0.6
typesafe-validator
Data validator with typescript.
Installation
pnpm add @typesafe-validator/core
Validation rules
Builtin
- number
- int
- bigint
- string
- boolean
- object
- array
- buffer
- enum
- ip
- uuid
- hash
- oneOf
- any
Core packages
Usage
import { rule, validate } from '@typesafe-validator/core';
const untrusted = { id: 10, name: 'foo', dangerous: 'rm -rf /' };
const trusted = await validate(untrusted, {
id: rule.int(),
name: rule.string(),
age: rule.int().optional(),
country: rule.string().default('China'),
});
trusted; // { id: 10, name: 'foo', country: 'China' }
typeof trusted; // { id: number; name: string; age?: number; country: string }
Mixin custom validator
import { Rule, Validator } from '@typesafe-validator/core';
declare module '@typesafe-validator/core' {
export interface Rule {
foo(): MyValidator;
}
}
Rule.extend('foo', () => new MyValidator());
export class MyValidator<T = any> extends Validator<T> {}
So that we can use custom validator with type annotation like builtin ones
import { rule } from '@typesafe-validator/core';
rule.foo(); // MyValidator<any>
Generate openapi-v3 document
import { rule, toDocument } from '@typesafe-validator/core';
const parameter = toDocument(rule.int());
parameter; // { required: true, schema: { type: 'integer' } }
const parameter = toDocument(rule.string().default('China'));
parameter; // { required: false, schema: { default: 'China', type: 'string' } }