1.1.12 • Published 5 years ago

sw-class-schema v1.1.12

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

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) //Additional parameters in JSON object won't throw an error
    
    @Min(12) @Max(12)
    age: number;
    
    @Contains("patrick")
    name: string;
    
    @ValidateIf(obj => obj.email != void 0) @IsEmail() //This is an optional field
    email: string;

    constructor() {
        super("age", "name", "email"); //Here all properties that need to be constructed/deconstructed
    }
            
}


class Post extends Schema {

    @Strict(true) //Strict mode
    
    @IsDefined() @ValidateNested() //Never forget to put @IsDefined() if you use @ValidateNested()
    user: User;
    
    @Length(5, 20)
    title: string;
    
    @Contains("hello") @Length(10, 200)
    text: string;
    
    @IsDatable() //This means either an ISO string date or a Date object
    @ToDate() //When an object is stringified, Date objects become ISO strings, so to reconstruct, we use ToDate formatter 
    date: Date;
    
    @IsDefined() @ValidateNested({each: true}) // Special case for arrays, see super as well
    users: Array<User>;
    
    constructor() { //Never forget it !
        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"}); //This will throw an error
1.1.12

5 years ago

1.1.11

5 years ago

1.1.10

6 years ago

1.1.9

7 years ago

1.1.8

7 years ago

1.1.7

7 years ago

1.1.6

7 years ago

1.1.5

7 years ago

1.1.4

7 years ago

1.1.3

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago