Now for us to actually use the bookRepository in our bookService.
File: src/domain/services/bookService.js
// Retrieve - one
const getBookById = async (bookId) => {
const book = await bookRepository.getById(bookId)
return book
}
6 - Events
None.
7 - Response
But wait! let's not forget the 404 validation we promised.
File: src/domain/services/bookService.js
// Retrieve - one
const getBookById = async (bookId) => {
if (!mongoose.Types.ObjectId.isValid(bookId)) {
// the id is invalid
throw new ApiException({
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.`]
})
}
const book = await bookRepository.getById(bookId)
if (!book) {
throw new ApiException({
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.