All files / src/middleware fileUpload.middleware.ts

81.48% Statements 22/27
88.88% Branches 8/9
100% Functions 3/3
80.95% Lines 17/21

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 222x 2x 2x 2x 2x 2x 2x 4x 2x 55x 27x 4x   23x       23x 2x 4x 2x  
// src/middleware/fileUpload.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { ValidationError } from '../services/db/errors.db';
 
/**
 * Middleware to check if a file was uploaded by multer.
 * @param fieldName The expected field name of the uploaded file.
 */
export const requireFileUpload =
  (fieldName: string) => (req: Request, res: Response, next: NextFunction) => {
    if (!req.file || req.file.fieldname !== fieldName) {
      // Use ValidationError for consistency with ADR-003.
      // The errorHandler will format this into a 400 response with a structured error.
      const validationIssue = {
        path: ['file', fieldName],
        message: `A file for the '${fieldName}' field is required.`,
      };
      return next(new ValidationError([validationIssue]));
    }
    next();
  };