Welcome to Part 4 of this review of the Pluralsight course RESTful Web Services with Node.js and Express by Jonathan Mills.
Node.js and Express gives us the ability to write lightweight, fast, scalable APIs quickly.
Also in this series:
Part 1 – What is REST?
Part 2 – Getting Data
Part 3 – Posting Data
Part 4 – Updating Data
Part 5 – Testing
Part 6 – HATEOAS
In this demo we write a put method using Book.findById and setting all the book properties to those from our request if there is no error.
In Postman we make a Put request and see that it is working.
the “__v”key comes from MongoDB and represents the version.
Now what if we only want to update a single property in the model, e.g. update the read value from false to true?
Instead of sending the entire contents of the book, we can make a PATCH request.
In bookRoutes we write a .patch method. Again this uses findById and instead of repeating ourselves over and over we use some middleware.
Middleware intercepts and processes a request, and then forwards that request onto the route.
We use middleware with app.use, and we are writing our own middleware here.
It does a findById and returns HTTP 500 response if there’s an error, or our book data as JSON if a book is found.
With this in replace we have implemented the Don’t Repeat Yourself principle.
We add a .patch method using a for loop over each piece of data in req.body
We test our patch method in Postman and see that it all works.
The final verb to add in bookRoutes.js.
We add a .delete method and this returns a 500 if there’s an error, or a 204 if successful.
Again we test this in Postman to show that this code is working correctly.