I implemented a simple server in NodeJS using TypeScript and ExpressJS. At present, in each endpoint, I check if the incoming request body matches the expected parameters in the following way: -
express.Router().post('/add', (req: Request, res: Response) => {
if (!req.body.operand1 || typeof req.body.operand1 !== 'number' ||
!req.body.operand2 || typeof req.body.operand2 !== 'number') {
res.send('Request body is invalid');
return;
}
const parameters = req.body;
res.send(parameters.operand1 + parameters.operand2);
}
But this would get tedious if there are many expected parameters in a given endpoint. What is the best way to achieve this?
EDIT
I edited this question because, before I had included some interfaces and the question looked similar to Detect whether object implement interface in TypeScript dynamically, which (understandably) confused people, while the scenario was different from that. There, the asker wanted to know if an object implements an interface. Here, I want to see if the body in a post request is the expected one.