Creating routes is a fairly straightforward process, we start by adding a new class book.js
in the /routes/api
folder.
Then, we need to import the book service, book model and router.
We should also add the following line:
This allows us to inherit the parameters defined in req.params
at the parent router.
Now, all we have to do is define our API endpoints. Let's create a route that will get us all the books:
Since we need to retrieve the data about all the books registered in the database, we create an HTTP request with a GET method. The URL /getBooks
is our API path.
Caution: /getBooks
is not the complete API path. In this case the complete API path is http://localhost:3000/api/user/getBooks
In fact, our newly created API path is appended to a previously defined path at the parent router. This router is located in the root directory inapp.js.
Next, we add two more routes, one for adding a book and another one to delete a book:
Here, our HTTP request method is a POST method since we will be sending data rather than retrieving it. We extract the title, author and ISBN from the request body. Then, we create an instance of a book with those attributes and we call the addBook()
function that we defined in our book service. If the request succeeds, we will respond with the message "Book added" otherwise "Book not added!" as well as attach a success indicator (a boolean variable in our case).
In this function, we changed the method of request is set to DELETE as we will be removing an entry from the database. This time, we extract the ISBN from the path rather than the body.
As always, we finish by exporting our router.