const express = require('express')
const router = express.Router()
const {
getAllBooks,
getBookById,
createABook,
updateABook
} = require('../controllers/book')
router.get('/', getAllBooks)
router.get('/:id', getBookById)
router.post('/', createABook)
// This is the new route we are adding in
router.put('/:id', updateABook)
Let's also create our controller so we can fill in the details later on.
File: src/controllers/book/updateABook.js
const catchException = require('../../utils/catchExceptions')
/**
* Updates an existing book listing by id.
*/
const updateABook = catchException(async (req, res) => {
// we'll fill in the details after we get each of the other layers ready
})
module.exports = updateABook
2 - Input Request
For the input request, this will seem very familiar. It's because this is the exact code we used for our createBookRequestDto.js with the exception of an additional id field.
const ApiException = require('../utils/ApiException')
const fields = [
'id',
'title',
'description',
'price',
'author',
'datePublished'
]
const updateBookRequestDto = (data) => {
const errors = []
fields.forEach((field) => {
if (!(field in data)) {
errors.push(`This DTO's property is required: ${field}.`)
}
})
if (errors.length > 0) {
throw new ApiException({
status: 'error',
code: 422,
message: 'Input fields are of not the correct form.',
data: null,
errors
})
}
return data
}
module.exports = updateBookRequestDto
3 - Middleware
File: src/routes/book.route.js
// We'll be adding in the isAuthenticated middleware and also our
// new middleware, the bookPermission middleware
router.put('/:id', isAuthenticated, bookPermission, updateABook)
As stated previously, we need a way to check if the request book to be updated does indeed belong to the currently authenticated user.
This will help us do so. Notice also that we are going to be using the bookService.getBookId method we created previously. This is a great functionality to reuse because the getBookById inherently has a check to see if the bookId is correct, otherwise it will throw an exception.
File: src/middleware/bookPermission.middleware.js
const globalResponseDto = require('../responses/globalResponseDto')
const catchExceptions = require('../utils/catchExceptions')
const bookService = require('../domain/services/book.service')
const bookPermission = catchExceptions(async (req, res, next) => {
// When updating or deleting a book, the book must belong to the user that created it
const bookId = req.params.id
const book = await bookService.getBookById(bookId)
// check to see if the current authenticated user's the owner of the
// requested bookId
if (req.session.user._id !== book.userId.toString()) {
res.status(401).json(
globalResponseDto({
status: 'error',
code: 401,
message:
'Access denied: you must be the owner of this book when updating or deleting it.',
data: null,
errors: [
'Access denied: you must be the owner of this book when updating or deleting it.'
]
})
)
}
next()
})
module.exports = bookPermission
4 - Validation
Again, this is very similar to the createBookValidator with the exception of an additional id field. You are probably wondering why we require all fields instead of a subset of them. Do recall that this is a PUT request, which means we must accept the entire resource into our API as we are re-updating the entire entity in database.
File: src/validators/updateBookValidator.js
const Validator = require('validatorjs')
const ApiException = require('../utils/ApiException')
/**
* @param {*} data {
* - id
* - title
* - description
* - price
* - author
* - datePublished
* }
*
* @returns Validator
*/
const updateBookValidator = (data) => {
const rules = {
title: 'required',
description: 'required',
price: 'required|numeric|min:1',
author: 'required',
datePublished: 'required'
}
const validator = new Validator(data, rules)
if (validator.fails()) {
let errors = []
for (const field in validator.errors.errors) {
errors = errors.concat(validator.errors.errors[field])
}
throw new ApiException({
message: 'There were errors with the validation',
status: 'error',
code: 400,
data: null,
errors
})
}
return validator
}
module.exports = updateBookValidator
5 - Domain
Yet again, this is similar to what we had before when we wrote the create method in our bookRepository and the createBook method in our bookService. We now do this for updating a book.