Skip to content

vitarn/tdv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

c899f5b · Jun 5, 2018

History

43 Commits
Apr 13, 2018
Jun 5, 2018
Jun 5, 2018
Apr 13, 2018
Apr 10, 2018
Jun 5, 2018
Mar 8, 2018
Apr 10, 2018
Jun 5, 2018
Jun 5, 2018
Apr 13, 2018
Jun 5, 2018

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: '[email protected]', profile: { displayName: 'Joe' } })

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

console.log(user.attempt())
{ id: 123, email: '[email protected]', profile: { displayName: 'Joe' } }

console.log(user.toJSON())
{ id: 123, email: '[email protected]', 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 }