express-body-params is decorator for handler functions to validate body before function called.
Use the package manager npm to install express-body-params decorator.
npm i express-body-params
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> {
...
}
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 })
}
}
- 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.
Parameter | Type |
---|---|
handleInside | Boolean |
params | IParamConfig[] |
export interface IParamConfig {
required?: boolean;
pattern?: RegExp;
min?: number;
max?: number;
type: ParamTypes;
name: string;
}
export declare class ParamError {
param: string;
message: string;
constructor(param: string, message: string);
}
export declare enum ParamTypes {
number = "number",
string = "string",
boolean = "boolean",
email = "email"
}
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.