Create Route

Creating routes is a fairly straightforward process, we start by adding a new class book.js in the /routes/apifolder.

Then, we need to import the book service, book model and router.

const Router = require("express").Router;
const bookService = require("../../services/book.service")();
const Book = require("../../models/Book");

We should also add the following line:

const router = Router({
  mergeParams: true,
});

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:

router.get("/getBooks", async(req, res) => {
  try {
    const books = await bookService.getBooks();
    res.send(books);
  } catch(err) {
    res.json({ success: false, msg: "Failed to get 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: /getBooksis 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:

//Route to create a book
router.post("/addBook", async(req, res, next) => {
    try {
        const {title, author, isbn} = req.body;
        await bookService.addBook(title, author, isbn);
        res.send({ success: true, msg: "Book Added"});
    } catch (err) {
        res.send({ success: false, msg: "Book not Added!", err})
    }
});

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).

// Route to delete a book
router.delete("/deleteBook/:isbn", async(req, res) => {
  try {
    const isbn = req.params.isbn;
    bookService.deleteBook(isbn);
    res.send({ success: true, msg: "Book deleted"})
  } catch (error) {
    res.send({ success: false, msg: "Book not added!"})
  }
});

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.

module.exports = router;

Last updated