But wait! let's not forget the 404 validation we promised.
File: src/domain/services/bookService.js
// Retrieve - oneconstgetBookById=async (bookId) => {if (!mongoose.Types.ObjectId.isValid(bookId)) {// the id is invalidthrownewApiException({ message:`the book with that id: ${bookId} does not exist.`, status:'failed', code:404, data:null, errors: [`the book with that id: ${bookId} does not exist.`] }) }constbook=awaitbookRepository.getById(bookId)if (!book) {thrownewApiException({ message:`the book with that id: ${bookId} does not exist.`, status:'failed', code:404, data:null, errors: [`the book with that id: ${bookId} does not exist.`] }) }return book}
As usual, here is our controller. Thanks to us doing the business logic validation in our domain layer, our controller is thin and free of clutter.
File: src/controllers/book.controller.js
constgetBookById=catchException(async (req, res, next) => {constbook=awaitbookService.getBookById(req.params.id)returnres.json(globalResponseDTO({ status:'success', code:200, message:`Book with the specified id.`, data: book, errors:null }) )})