@grace-js/grace
Version:
An opinionated API framework
61 lines • 1.97 kB
JavaScript
import { z } from 'zod';
export function convertToBytes(fileSize) {
const { value, unit } = fileSize;
switch (unit) {
case 'B':
return value;
case 'KB':
return value * 1024;
case 'MB':
return value * 1024 * 1024;
case 'GB':
return value * 1024 * 1024 * 1024;
case 'TB':
return value * 1024 * 1024 * 1024 * 1024;
default:
throw new Error('Invalid file size unit.');
}
}
export function validateFile(options, value) {
if (!(value instanceof Blob)) {
return false;
}
if (options.minimumSize && value.size < convertToBytes(options.minimumSize)) {
return false;
}
if (options.maximumSize && value.size > convertToBytes(options.maximumSize)) {
return false;
}
if (options.mimetype) {
if (typeof options.mimetype === 'string') {
if (!value.type.startsWith(options.mimetype)) {
return false;
}
}
else {
for (const item of options.mimetype) {
if (value.type.startsWith(item)) {
return true;
}
}
return false;
}
}
return true;
}
export const zg = Object.assign({
file: (options) => z.custom((data) => {
return validateFile(options, data);
}),
files: (options) => z.array(z.custom((data) => {
return validateFile(options, data);
})).min(options.minimumFiles ?? 0).max(options.maximumFiles ?? Infinity),
base64: (options) => z.string().refine((data) => {
if (data.startsWith('data:')) {
const [mimetype, base64] = data.split(';base64,');
return validateFile(options, new Blob([atob(base64)], { type: mimetype }));
}
return validateFile(options, new Blob([data], { type: 'application/octet-stream' }));
})
}, z);
//# sourceMappingURL=zod.js.map