Skip to content

vitarn/tdv

Repository files navigation

tdv

Typescript (definition|decorator) validator base on Joi

License NPM Build Status Coverage Status Greenkeeper badge

Example

tsconfig.json

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
    },
}
import { Schema, required, optional } from 'tdv'

class User extends Schema {
    @required
    id: number

    @required(Joi => Joi.string().email())
    email: string

    @required
    profile: Profile
}

class Profile extends Schema {
    @optional
    displayName?: string
}

const user = new User({ id: 123, email: 'foo@example.com', profile: { displayName: 'Joe' } })

console.log(user.validate())
{ error: null,
    value: { id: 123, email: 'foo@example.com', profile: { displayName: 'Joe' } },
    then: [Function: then],
    catch: [Function: catch] }

console.log(user.attempt())
{ id: 123, email: 'foo@example.com', profile: { displayName: 'Joe' } }

console.log(user.toJSON())
{ id: 123, email: 'foo@example.com', profile: { displayName: 'Joe' } }

const user2 = new User({})

console.log(user2.validate())
{ error:
        { ValidationError: child "id" fails because ["id" is required]
        at error stack...
        isJoi: true,
        name: 'ValidationError',
        details: [ [Object] ],
        _object: { id: undefined, profile: undefined },
        annotate: [Function] },
    value: { id: undefined, profile: undefined },
    then: [Function: then],
    catch: [Function: catch] }

console.log(user.attempt())
{ ValidationError: {
    "id" [1]: -- missing --
    }

    [1] "id" is required
        at error stack...
    isJoi: true,
    name: 'ValidationError',
    details:
        [ { message: '"id" is required',
            path: [Array],
            type: 'any.required',
            context: [Object] } ],
    _object: { id: undefined, profile: undefined },
    annotate: [Function] }

console.log(user.toJSON())
{ id: undefined, profile: undefined }

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published