tsoa-zod-validator
Version:
Zod validation decorators for tsoa
53 lines (52 loc) • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFileSize = parseFileSize;
exports.isValidFileType = isValidFileType;
/**
* Unit sizes in bytes
*/
const SIZE_UNITS = {
B: 1,
KB: 1024,
MB: 1024 * 1024,
GB: 1024 * 1024 * 1024,
TB: 1024 * 1024 * 1024 * 1024,
};
/**
* Parses a file size string (e.g., '10MB') to bytes
* @param size The size to parse
* @returns The size in bytes
*/
function parseFileSize(size) {
// If size is already a number, return it
if (typeof size === 'number') {
return size;
}
// Parse the size string
const match = size.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)?$/i);
if (!match) {
throw new Error(`Invalid file size format: ${size}`);
}
const value = parseFloat(match[1]);
const unit = (match[2] || 'B').toUpperCase();
if (!(unit in SIZE_UNITS)) {
throw new Error(`Invalid file size unit: ${unit}`);
}
return value * SIZE_UNITS[unit];
}
/**
* Validates if a file's MIME type is in the allowed types list
* @param fileMimeType The file's MIME type
* @param allowedTypes The list of allowed MIME types
* @returns True if the file type is allowed, false otherwise
*/
function isValidFileType(fileMimeType, allowedTypes) {
return allowedTypes.some((type) => {
// Handle wildcard types like 'image/*'
if (type.endsWith('/*')) {
const typePrefix = type.split('/')[0];
return fileMimeType.startsWith(`${typePrefix}/`);
}
return type === fileMimeType;
});
}