i made this middleware, and trying to test that, but when i send a body without any key, it won't work, always do the default
this is the middleware:
import { IMiddlewaresRules } from "../IMiddlewaresRules";
import { Request, Response, NextFunction } from "express";
export class VerifyRequestsBody implements IMiddlewaresRules {
verifyBodyFigure(
req: Request,
res: Response,
next: NextFunction
): Response | any {
const data = req.body.data;
console.log(data.name);
switch (data) {
case !data.name:
return res.status(400).json({ message: "Missing name" });
case !data.category:
return res.status(400).json({ message: "Missing category" });
case !data.price:
return res.status(400).json({ message: "Missing price" });
case !data.specifications:
return res.status(400).json({ message: "Missing specifications" });
case !data.releaseInfo:
return res.status(400).json({ message: "Missing releaseInfo" });
case !data.serieID:
return res.status(400).json({ message: "Missing serieID" });
case !data.manufacturerID:
return res.status(400).json({ message: "Missing manufacturerID" });
default:
return next();
}
}
}
body
{
"data": {
"category": "1/7th Scale",
"price": "19,690",
"specifications": "Painted plastic 1/7 scale complete product with stand included. Approximately 250mm in height.",
"releaseInfo": "2022/10",
"details": "Yui Kotegawa makes a dazzling appearance in an idol costume with a flustered look on her face! From To Love-Ru Darkness comes a 1/7 scale figure of Yui Kotegawa! Dressed in a dazzling idol costume quite different from her typical attire, Yui has been captured in figure form with an adorable, flustered expression. Yui's blue and white sailor suit features anchor decorations on her hat and boots created with metallic paintwork, lending them a weighty appearance. Her long flowing hair and dynamic pose have been meticulously sculpted, perfectly capturing Yui's charm The figure also com",
"serieID": 9,
"manufacturerID": 5
}
}
i delete the name of the body, but middleware don't catch that, always return next and i can't find what is going on, anyone see what i'm doing wrong?
And any tip how to type the return of the middleware, i put any because i dont know how to set in the return
FULLL CODE HERE: https://github.com/DanielTrybe/backend-figures/blob/1.2.0-middleware/src/middlewares/Rules/VerifyRequestBody.ts
CodePudding user response:
If data
is usually an object, and you want to check if the .name
property exists, then this statement:
switch(data) {
case !data.name:
break;
will never do anything because !data.name
evaluates to true
. and {data == true}
evaluates to false.
You could replace switch(data)
to with switch(true)
, but it would still be a pretty weird use of switch, and it gets weird if you have falsy property values.
My recommendation would be to adopt something like json-schema instead.