tdv
TypeScript icon, indicating that this package has built-in type declarations

0.4.1 • Public • Published

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())
{ errornull,
    value{ id123, email'foo@example.com', profile{ displayName'Joe' } },
    then[Functionthen],
    catch[Functioncatch] }
 
console.log(user.attempt())
{ id123, email'foo@example.com', profile{ displayName'Joe' } }
 
console.log(user.toJSON())
{ id123, email'foo@example.com', profile{ displayName'Joe' } }
 
const user2 = new User({})
 
console.log(user2.validate())
{ error:
        { ValidationErrorchild "id" fails because ["id" is required]
        at error stack...
        isJoitrue,
        name'ValidationError',
        details[ [Object] ],
        _object{ idundefined, profileundefined },
        annotate[Function] },
    value{ idundefined, profileundefined },
    then[Functionthen],
    catch[Functioncatch] }
 
console.log(user.attempt())
{ ValidationError{
    "id" [1]-- missing --
    }
 
    [1] "id" is required
        at error stack...
    isJoitrue,
    name'ValidationError',
    details:
        [ { message: '"id" is required',
            path: [Array],
            type: 'any.required',
            context: [Object] } ],
    _object{ idundefined, profileundefined },
    annotate[Function] }
 
console.log(user.toJSON())
{ idundefined, profileundefined }

Readme

Keywords

none

Package Sidebar

Install

npm i tdv

Weekly Downloads

1

Version

0.4.1

License

MIT

Unpacked Size

30.1 kB

Total Files

16

Last publish

Collaborators

  • colder