Step 11

Let's refactor our code and store all the middlewares in a separate module.

Add a file, middleware.js, to server/util folder:

const ApiError = require("../model/ApiError"); const { verifyToken, decodeToken, parseBearer } = require("./token"); const checkAdmin = async (req, res, next) => { const { authorization } = req.headers; const token = authorization ? parseBearer(authorization) : ""; const valid = await verifyToken(token); const user = decodeToken(token); if (!valid || user.role !== "ADMIN") { next(new ApiError(403, "You are not authorized to perform this action.")); } next(); }; const checkToken = async (req, res, next) => { const { authorization } = req.headers; const token = authorization ? parseBearer(authorization) : ""; const valid = await verifyToken(token); if (!valid) { next(new ApiError(403, "You are not authorized to perform this action.")); } req.user = decodeToken(token); next(); }; const globalErrorHandler = (err, req, res, next) => { if (err) { // debug(err); return res .status(err.status || 500) .json({ message: err.message || "Internal server error!" }); } next(); }; module.exports = { checkToken, checkAdmin, globalErrorHandler, };

Make the following updates:

  1. Remove checkAdmin from server/routes/users.js (and related import stataments). Instead, import checkAdmin from ../util/middleware.
  2. Remove checkToken from server/routes/notes.js (and related import stataments). Instead, import checkToken from ../util/middleware.
  3. Update server/index.js (and related import stataments). Instead, import checkToken from ../util/middleware.
+ const { globalErrorHandler } = require("./util/middleware"); - // Global error handler! - app.use((err, req, res, next) => { - if (err) { - // debug(err); - return res - .status(err.status || 500) - .json({message: err.message || "Internal server error!"}); - } - next(); - }); + app.use(globalErrorHandler);

Save the changes and rerun the tests to ensure the refactoring has not intriduced a defect.