express-body-params
TypeScript icon, indicating that this package has built-in type declarations

1.0.10 • Public • Published

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

Parameter Type
handleInside Boolean
params IParamConfig[]

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

Package Sidebar

Install

npm i express-body-params

Weekly Downloads

0

Version

1.0.10

License

MIT

Unpacked Size

14 kB

Total Files

6

Last publish

Collaborators

  • stveljko012