express-image-validator
Version:
Validator of various image parameters in Express.js applications
70 lines (69 loc) • 3.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.runValidators = runValidators;
const files_1 = require("./files");
const normalizeValidationOptions_1 = require("../utils/normalizeValidationOptions");
/**
* Runs all validator functions for a specific field and collects validation errors.
*
* Execution flow:
* 1. Normalizes the provided schema into `ValidationOptions` (unless `notNormalizeOptions` is `true`).
* 2. Runs all field-level validators with the entire array of files.
* - If a validator sets `breakValidation`, file-level validation is skipped.
* 3. If no break occurred, runs all file-level validators for each individual file.
* 4. Collects all errors into a single array, appends them to `req.IMAGE_VALIDATION_RESULTS`,
* and returns that array.
*
* Requirements:
* - At least one validator function (field-level or file-level) must be provided,
* otherwise an error is thrown.
* - `req.files[field]` is normalized into an array internally.
*
* @param { Request } req Express request object.
* @param { string } field Name of the multipart/form-data field to validate.
* @param { ValidationOptions } schema Validation options.
* @param { ValidatorFunctions } validators Validator functions separated into field-level and file-level.
* @param { boolean } [notNormalizeOptions=false] If `true`, skips normalization of `schema` and uses it directly.
* @returns { Promise<ValidationError[]> } Collected validation errors.
* @throws { Error } If no validator functions are provided.
*/
async function runValidators(req, field, schema, validators, notNormalizeOptions = false) {
if (!validators.fieldLevel.length && !validators.fileLevel.length) {
throw new Error('At least one validator function must be passed to `runValidators`');
}
const files = (0, files_1.toFileArray)(req.files?.[field]);
const options = notNormalizeOptions
? schema
: (0, normalizeValidationOptions_1.normalizeValidationOptions)(schema);
const errors = [];
let validationBreaked = false;
for (let i = 0; i < validators.fieldLevel.length; i++) {
const result = await validators.fieldLevel[i](field, files, options);
if (result.errors.length > 0) {
errors.push(...result.errors);
}
if (result.breakValidation) {
validationBreaked = true;
break;
}
}
if (!validationBreaked) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
for (let j = 0; j < validators.fileLevel.length; j++) {
const result = await validators.fileLevel[j](field, file, options);
if (result.errors.length > 0) {
errors.push(...result.errors);
}
if (result.breakValidation) {
break;
}
}
}
}
if (!req.IMAGE_VALIDATION_RESULTS) {
req.IMAGE_VALIDATION_RESULTS = [];
}
req.IMAGE_VALIDATION_RESULTS.push(...errors);
return errors;
}