Step 11
We need to provide input validation when designing our API. In particular when we create, update, or delete resources.
We can perform input validation inside our route handler or delegate that to NoteDao
.
I've gone with the latter; update NoteDao.create
method:
create(content, author) {
if (!content || !author) {
throw new Error("Invalid attributes");
}
const note = new Note(content, author);
note._id = this.nextID();
this.notes.push(note);
return note;
}
If either content
or author
are falsy values (null
, undefined
, or empty string), and error will be thrown.
Update the route handler in index.js
to include error handling:
app.post("/api/notes", (req, res) => {
const content = req.body.content;
const author = req.body.author;
try {
const note = notes.create(content, author);
res.status(201).json(note);
} catch (error) {
res.status(400).send(error.message);
}
});
Notice I set the status code to 400 before sending the error message.
In Postman, test the input validation by sending a request to api/notes
endpoint with insufficient or invalid attributes.