1.0.2 • Published 3 years ago

model-decorators v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

Model Decorators

A library of decorators to create a model that validates data and exposes some of them for parsing and serialization.

Example

import {isNumber, isString, Model, ensure, expose, report} from "./model";

class Person extends Model {
    @ensure(isNumber(0))
    nerdiness: number = 0

    @expose
    @ensure(isString({
        maxLength: 50
    }))
    name: string

    @expose
    @ensure(
        isNumber(0, 140),
        report(
            (a: number) => a % 2 == 0,
            (a: number) => TypeError(`number ${a} is not an even number`)))
    age: number
}

let person = new Person({
    name: "Alex",
    age: 21
})
let other = new Person({
    name: "Mike",
    age: 22
})

console.log(other.json)

How To Use

@expose:

Exposes field for serialization/deserialization

@ensure:

interface Validator {
    (val: any): boolean
}

function ensure (...validators: Validator[]): PropertyDecorator {/*...*/}

Validates the data whenever the field is set, based on the argument validator functions ({ (val: any): boolean }). If the result is false, a TypeError will be thrown

isString/isNumber:

const isString = ({
    maxLength = Infinity,
    minLength = 0,
    pattern = null
}: IsStringOpts) => (
    s: any
): s is string => {/*...*/}

const isNumber = (
    lowerBound: number = - Infinity,
    upperBound: number = Infinity
) => (
    n: any
): n is number => {/*...*/}

Factories for typescript val is string and val is number validator functions

report:

export function report(validator: Validator, error: Error)
export function report(validator: Validator, error: { (val: any): Error })
export function report(validator: Validator, error: Error | { (val: any): Error }) {/*...*/}

factory for special validator, which throws the error defined in the second argument whenever the data is invalid. The second argument can either be the error itself, or a factory of errors based on the value given