All files / src/middleware isOwner.js

100% Statements 15/15
100% Branches 6/6
100% Functions 1/1
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 324x 4x     12x 12x     12x 1x     11x       11x 1x     10x 1x     9x 9x   3x       4x
const prisma = require("../lib/prisma");
const { NotFoundError, ForbiddenError } = require("../lib/errors");
 
async function isOwner (req, res, next) {
  try { 
    const id = Number(req.params.questionId);
    
    // NaN CHECK
    if (isNaN(id)) {
      throw new NotFoundError("Question not found"); 
    }
 
    const question = await prisma.question.findUnique({
      where: { id },
    });
 
    if (!question) {
      throw new NotFoundError("Question not found");
    }
 
    if (Number(question.userId) !== Number(req.user.userId)) {
      throw new ForbiddenError("You can only modify your own questions");
    }
 
    req.question = question;
    next();
  } catch (error) { // CATCH AND FORWARD ERROR
    next(error);
  }
}
 
module.exports = isOwner;