UNPKG

express-image-validator

Version:

Validator of various image parameters in Express.js applications

47 lines (46 loc) 1.93 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateAspectRatio = void 0; const sharp_1 = __importDefault(require("sharp")); const aspectTolerance_1 = require("../constants/aspectTolerance"); const aspectRatio_1 = require("./errors/aspectRatio"); /** * Validates that the uploaded image matches the specified aspect ratio. * Returns an error if the difference exceeds the allowed tolerance `ASPECT_TOLERANCE` or if the image cannot be read. * @type { FileValidatorFunction } * @param { string } field Field name. * @param { UploadedFile } file The uploaded image file. * @param { ValidationOptions } options Validation options containing `aspectRatio`. * @returns { ValidationResult | Promise<ValidationResult> } Validation result as `Promise`. */ const validateAspectRatio = (field, file, { aspectRatio }) => { if (!aspectRatio) { return { errors: [] }; } return (0, sharp_1.default)(file.data) .metadata() .then((meta) => { if (!meta.width || !meta.height) { return { errors: [(0, aspectRatio_1.unableReadError)(field, file.name, aspectRatio)], }; } const actualAspectRatio = meta.width / meta.height; const difference = Math.abs(actualAspectRatio - aspectRatio); if (difference > aspectTolerance_1.ASPECT_TOLERANCE) { return { errors: [ (0, aspectRatio_1.largeDiffError)(field, file.name, actualAspectRatio, aspectRatio), ], }; } return { errors: [] }; }) .catch(() => ({ errors: [(0, aspectRatio_1.readingError)(field, file.name, aspectRatio)], })); }; exports.validateAspectRatio = validateAspectRatio;