UNPKG

express-image-validator

Version:

Validator of various image parameters in Express.js applications

64 lines (63 loc) 2.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateOptions = generateOptions; exports.normalizeValidationOptions = normalizeValidationOptions; const typeChecks_1 = require("./typeChecks"); const imageMimeTypes_1 = require("../constants/imageMimeTypes"); /** * Extracts validation options from a `FieldSchema`. * If options are missing, returns an empty object. * @param { FieldSchema } schema Field schema. * @returns { ValidationOptions } Validation options (may be incomplete). * @internal */ function getOptionsObj(schema) { const options = schema?.options ?? {}; return options; } /** * Generates a fully populated options object with defaults applied. * Converts sizes from megabytes to bytes. * @param { ValidationOptions? } options Input options. * @returns { ValidationOptions } Normalized options with defaults filled in. */ function generateOptions(options) { return { limit: options?.limit ?? null, minSize: options?.minSize ? options.minSize * 1024 * 1024 : 0, maxSize: options?.maxSize ? options.maxSize * 1024 * 1024 : null, required: options?.required ?? false, aspectRatio: options?.aspectRatio ?? null, allowedMimeTypes: options?.allowedMimeTypes ?? imageMimeTypes_1.imageMimeTypes, }; } /** * Normalizes validation options or a full field schema. * - Ensures values are consistent. * - Throws errors if invalid values are provided. * - Returns a complete `ValidationOptions` object with defaults applied. * @param { ValidationOptions | FieldSchema } schema Options or schema. * @returns { ValidationOptions } Normalized validation options. * @throws { Error } If values are inconsistent or invalid. */ function normalizeValidationOptions(schema) { const options = schema && Object.prototype.hasOwnProperty.call(schema, 'name') ? getOptionsObj(schema) : schema; if ((0, typeChecks_1.isNumber)(options?.limit) && (!Number.isInteger(options.limit) || options.limit < 1)) { throw new Error('The limit must be a non-zero positive integer'); } if ((0, typeChecks_1.isNumber)(options?.maxSize) && options.maxSize <= 0) { throw new Error('The maximum size must be a non-negative number'); } if ((0, typeChecks_1.isNumber)(options?.minSize)) { if (options.minSize < 0) { throw new Error('The minimum size must be a positive number'); } if (options.maxSize && options.minSize > options.maxSize) { throw new Error(`The minimum size must not exceed the maximum size. Set minSize = ${options.minSize}`); } } return generateOptions(options); }