Step 13
Let's include a route to update a note.
| Update Note | |
|---|---|
| HTTP Method | PUT |
| API Endpoint | /api/notes/:noteId |
| Request Path Parameter | noteId |
| Request Query Parameter | |
| Request Body | JSON object (note attributes) |
| Response Body | JSON object (updated note) |
| Response Status | 200 |
Similar to how we updated NoteDao.create to provide input validation, we must update NoteDao.update method:
update(id, content, author) {
if (!content || !author) {
throw new Error("Invalid attributes");
}
const index = this.notes.findIndex((note) => note._id === id);
if (index !== -1) {
this.notes[index].content = content;
this.notes[index].author = author;
return this.notes[index];
}
return null;
}
Add the following route to index.js:
app.put("/api/notes/:id", (req, res) => {
const id = Number.parseInt(req.params.id);
const content = req.body.content;
const author = req.body.author;
try {
const note = notes.update(id, content, author);
if (note) {
res.json(note);
} else {
res.status(404).send("Resource not found!");
}
} catch (error) {
res.status(400).send(error.message);
}
});
Notice I set two error status code: (400) for invalid request and (404) for invalid ID number (resource not found).
In Postman, test this endpoint by attempting to update a note that exist.

Also, test by requesting to update a note that does not exist.

Finally, test the endpoint with insufficient or invalid attributes.
