Level 24: Implement DELETE /items/:id
- Remove a record by
id and return 200 when found.
- Use the
filter pattern to create a new array without the deleted item. Replace the array with the filtered array. (See the “Show me” for more.)
- Respond with
404 and a friendly error JSON when the id is missing.
- Remember: Apply the filter pattern to your own resource array, not
itemsStorage.
Show Me: complete DELETE route
app.delete('/items/:id', (req, res) => {
console.log("Deleting " + req.params.id)
// Find the item first to check if it exists
const item = itemsStorage.find((entry) => entry.id === req.params.id);
// If not found, return 404
if (!item) {
return res.status(404).json({ error: 'Item not found' });
}
// TODO: Delete the item from your storage.
// Return success response
res.status(200).json({ message: 'Item deleted successfully' });
});
Show Me: delete using filter pattern
const item = itemsStorage.find((entry) => entry.id === req.params.id);
if (!item) return res.status(404).json({ error: 'Item not found' });
// Use filter to create a new array without the deleted item
// The filter pattern keeps all items where id does NOT match
itemsStorage = itemsStorage.filter((entry) => entry.id !== req.params.id);
res.status(200).json({ message: 'Item deleted successfully' });