I have to build an API with Node and express as package with the following requirements:
DELETE on
/api/posts— there will be one query parameters:id. If the server has a post with the given ID, it should remove it and the response should be only the 200 status code. No other posts should be affected; in particular, their IDs won't change. If the server did not have a post with the given ID, the response should be the 404 status code.
I have the following code that works ok
app.delete('/api/posts', (req, res) => {
let id = req.query.id;
if (typeof id !== 'number')
id = parseInt(id, 10);
let index;
for (let i = 0; i < posts.length; i += 1) {
if (posts[i].id === id) {
index = i;
break;
}
}
if (index == null) {
res.status(404).send();
return;
}
posts.splice(index, 1);
res.json(posts);
});
My question is, if this approach is correct or the code can be improved furthermore? I just started to learn about API's and Node....