1.0.10 • Published 5 years ago

express-body-params v1.0.10

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

express-body-params

express-body-params is decorator for handler functions to validate body before function called.

Installation

Use the package manager npm to install express-body-params decorator.

npm i express-body-params

Usage

Skip method call if body is not valid and send status 400 with errors:

import { Params, ParamTypes } from 'express-body-params';


// SET THIS PARAMETER TO TRUE
@Params(true, [
    { name: "email", type: ParamTypes.email, required: true },
    { name: "password", type: ParamTypes.string, required: true }
])
async login(req: any, res: any): Promise<void> {
	...
}

Call method call if body is not valid and pass errors to it:

import { Params, ParamTypes, ParamError } from 'express-body-params';


// SET THIS PARAMETER TO FALSE
@Params(false, [
    { name: "email", type: ParamTypes.email, required: true },
    { name: "password", type: ParamTypes.string, required: true }
])
async login(req: any, res: any): Promise<void> {
    if (req.validBody) {
        ...
    } else { 
        const errors: ParamError[] = req.bodyErrors;
        res.status(400).send({ errors })
    }
}

Optional checks

  • required - Checks if param exists.
  • pattern - Checks if param match the passed pattern.
  • min/max- Checks length of string if string type is setted or compare numbers for type number.

Parameters

ParameterType
handleInsideBoolean
paramsIParamConfig[]

Types

IParamConfig

export interface IParamConfig {
    required?: boolean;
    pattern?: RegExp;
    min?: number;
    max?: number;
    type: ParamTypes;
    name: string;
}

ParamError

export declare class ParamError {
    param: string;
    message: string;
    constructor(param: string, message: string);
}

ParamTypes

export declare enum ParamTypes {
    number = "number",
    string = "string",
    boolean = "boolean",
    email = "email"
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Please star me on github.

License

MIT

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.0

5 years ago