sw-class-schema
Useful helper to construct and deconstruct objects over http requests.
This module re-exports validators from Swanest' class-validator fork and sanitzers from class-sanitizer
List of usable types
Check out class-validator doc.
Install
npm i sw-class-schema --save
Use-case
Suppose you have an User
that is posting some Posts
import {
Schema,
Min,
Max,
Contains,
ValidateNested,
IsDefined,
IsDate,
Length,
ValidateIf,
IsEmail,
IsFQDN, Strict, IsDatable, ToDate
} from 'sw-class-schema';
class User extends Schema {
@Strict(false)
@Min(12) @Max(12)
age: number;
@Contains("patrick")
name: string;
@ValidateIf(obj => obj.email != void 0) @IsEmail()
email: string;
constructor() {
super("age", "name", "email");
}
}
class Post extends Schema {
@Strict(true)
@IsDefined() @ValidateNested()
user: User;
@Length(5, 20)
title: string;
@Contains("hello") @Length(10, 200)
text: string;
@IsDatable()
@ToDate()
date: Date;
@IsDefined() @ValidateNested({each: true})
users: Array<User>;
constructor() {
super({user: User}, "title", "text", "date", {user: [User]});
}
}
toSchema()
This sync method returns an object and recursively schematize inner objects.
let post = new Post();
post.title = "welcome";
post.user = new User();
post.toSchema();
fromSchema()
This async static method returns a promise of instance.
let post = await Post.fromSchema<Post>({title:"hello"});