@grace-js/grace
Version:
An opinionated API framework
66 lines • 2.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.zg = exports.validateFile = exports.convertToBytes = void 0;
const zod_1 = require("zod");
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.');
}
}
exports.convertToBytes = convertToBytes;
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;
}
exports.validateFile = validateFile;
exports.zg = Object.assign({
file: (options) => zod_1.z.custom((data) => {
return validateFile(options, data);
}),
files: (options) => zod_1.z.array(zod_1.z.custom((data) => {
return validateFile(options, data);
})).min(options.minimumFiles ?? 0).max(options.maximumFiles ?? Infinity),
base64: (options) => zod_1.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' }));
})
}, zod_1.z);
//# sourceMappingURL=zod.js.map