0.0.6 • Published 1 year ago

@typesafe-validator/core v0.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

typesafe-validator

Data validator with typescript.

node-current (scoped) npm peer typescript version GitHub Workflow Status (branch) Codecov npm npm npm bundle size (version) License Code Style

Installation

pnpm add @typesafe-validator/core

Validation rules

Builtin

  • number
  • int
  • bigint
  • string
  • boolean
  • object
  • array
  • buffer
  • enum
  • email
  • 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' } }
0.0.6

1 year ago

0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago