UNPKG

express-image-validator

Version:

Validator of various image parameters in Express.js applications

37 lines (36 loc) 1.7 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateMimeType = void 0; const file_type_1 = __importDefault(require("file-type")); const isSvg_1 = require("../utils/isSvg"); const mimeType_1 = require("./errors/mimeType"); /** * Validates that the uploaded file has an allowed MIME type and that the file's buffer * matches the declared MIME type. Special handling is included for SVG files. * @type { FileValidatorFunction } * @param { string } field Field name. * @param { UploadedFile } file The uploaded file to validate. * @param { ValidationOptions } options Validation options containing `allowedMimeTypes`. * @returns { Promise<ValidationResult> } Validation result as `Promise`. */ const validateMimeType = async (field, file, { allowedMimeTypes }) => { const allowedTypes = allowedMimeTypes; const svgAllowed = allowedTypes.includes('image/svg+xml'); const errors = []; if (!allowedTypes.includes(file?.mimetype)) { errors.push((0, mimeType_1.notSupportedError)(field, allowedTypes, file?.mimetype, file?.name)); return { errors }; } if (svgAllowed && (0, isSvg_1.isSvg)(String(file.data))) { return { errors }; } const realBufferType = await file_type_1.default.fromBuffer(file.data); if (!realBufferType || realBufferType.mime !== file.mimetype) { errors.push((0, mimeType_1.notRealBufferError)(field, file.mimetype, realBufferType?.mime, file.name)); } return { errors }; }; exports.validateMimeType = validateMimeType;