[Question] Is there a way to use with express-validator?
Closed this issue · 4 comments
Hi.
First of all, I must thank your work. To someone familiarized with Spring and Annotations, your express based lib looks awesome.
I have been trying to work with express-validator inside controllers but I'm not able. As middlewares, I use checks inside @Middleware annotation but, when I send an url request with empty body, any check is done and everytime OK response is sent. My piece of code looks like:
@Controller('vehicle/:vehicle_id/engine')
@ClassOptions({mergeParams: true})
export class VehicleEngineController {
@Post()
@Middleware([body('time').exists({checkNull: true}).withMessage('Time is required'),
body('registration').exists({checkNull: true}).withMessage('Registraton is required')])
private async insertData(req: Request, res: Response) {
return res.status(200).send(`Receive Data from Vehicle ${req.params.vehicle_id}`);
}
}
Maybe, I'm missing or doing something wrong but I can't find a way. Is possible to work express-validator?? Could you guide me why?
Thanks.
Bye.
Environment:
Windows 10
NodeJS 10.16.0
OvernigthJS 1.6.9
With express-validators, isn't it done more like check('something').not().isEmpty()
. I think body('time').exists({checkNull: true})
is checking to see if it is null. I'm not sure though cause I haven't used express-validators before.
Thanks for reply @seanpmaxwell.
I just try your suggestion but again any error is thrown if my body is empty. Now, my controller looks like:
@Controller('vehicle/:vehicle_id/engine')
@ClassOptions({mergeParams: true})
export class VehicleEngineController {
@Post()
@Middleware(check('time').not().isEmpty())
private async insertData(req: Request, res: Response) {
return res.status(200).send(`Receive Data from Vehicle ${req.params.vehicle_id}`);
}
}
However, If I code my own validator function and pass through @Middleware, it works perfectly. I don't know if, maybe, there is any problem with express-validator and annotations.
Thank you.
This isn't related to express-validator
, but I'm using a custom validator like this, in case it helps:
@Controller("users")
export class UserController {
@Put()
@Middleware(
validator(
{
name: Joi.string(),
email: Joi.string().required()
},
"body"
)
)
async put(req: Request, res: Response) {
res
.status(CREATED)
.json({ success: true, message: "user-created" });
}
}
The above example validates req.body
and uses the following validator
middleware:
import { Request, Response, NextFunction } from "express";
import Joi from "@hapi/joi";
export const validator = (
schemaMap: Joi.SchemaMap,
type: "body" | "params" | "query"
) => {
return (req: Request, res: Response, next: NextFunction) => {
let data: any;
switch (type) {
case "params":
data = req.params;
break;
case "query":
data = req.query;
break;
default:
data = req.body;
break;
}
const schema = Joi.object().keys(schemaMap);
const result = Joi.validate(data, schema);
if (result.error) throw new Error(`joi:${JSON.stringify(result.error)}`);
next();
};
};
Hey man sorry for the late response but I think you using express validators wrong. You forgot this line
validationResult(req).throw();
. I added an example to the sample-project and it's working fine.
@Get('debug/express-validators')
@Middleware(check('name').exists())
private async practiceValidators(req: Request, res: Response) {
try {
validationResult(req).throw();
return res.status(OK).json({
message: 'Hello from NodeJS ' + req.body.name,
});
} catch (err) {
Logger.Err(err, true);
return res.status(BAD_REQUEST).json({
error: err.message,
});
}
}