Step 8
Here is the handler for the HTTP GET request through /api/notes
endpoint:
router.get("/api/notes", (req, res) => {
const author = req.query.author;
notes
.readAll(author)
.then((notes) => res.json({ data: notes }))
.catch((err) => errorHandler(res, 500, err));
});
Notice we are using the Promise pattern for dealing with async operations of notes
object (instance of NoteDao
).
Also note the use of the helper function errorHandler
which is implemented as follows:
function errorHandler(res, status, error) {
res.status(status).json({
errors: [
{
status: status,
detail: error.message || error,
},
],
});
}
The status code 500
means "Internal Server Error"; it indicates that our server encountered an unexpected condition that prevented it from fulfilling the request. This is the only plausible explanation where the simple GET request to read all notes has failed! It must be an issue with our database or the server connecting to the database, etc. (The fault is on our side!)
Similarly, we can implement the handler for the HTTP GET request through /api/notes/:courseId
endpoint:
router.get("/api/notes/:id", (req, res) => {
const id = req.params.id;
notes
.read(id)
.then((note) => res.json({ data: note }))
.catch((err) => errorHandler(res, 500, err));
});