115 lines
2.6 KiB
TypeScript
115 lines
2.6 KiB
TypeScript
import { t } from '@lingui/macro';
|
|
import { RuleObject } from 'antd/es/form';
|
|
import { castArray } from 'lodash-es';
|
|
import {
|
|
FILE_SIZE_LIMIT,
|
|
IMAGE_EXTENSIONS,
|
|
IMAGE_SIZE_LIMIT,
|
|
isFileUnderLimit,
|
|
isImageFile,
|
|
isZipFile,
|
|
} from './file';
|
|
import { bytesToMegabytes } from './storage';
|
|
|
|
type Validator = (
|
|
rule: RuleObject,
|
|
value: unknown,
|
|
callback: (error?: string) => void,
|
|
) => Promise<void | any> | void;
|
|
type OneOrArray<T> = T | T[];
|
|
|
|
export const zipFilesValidator: Validator = (rule, value: OneOrArray<File>) => {
|
|
const files = castArray<File>(value);
|
|
const isValidZip = files.every((file: File) => isZipFile(file));
|
|
if (isValidZip) {
|
|
return Promise.resolve();
|
|
}
|
|
return Promise.reject(
|
|
new Error(t`You are only allowed to upload .zip file.`),
|
|
);
|
|
};
|
|
|
|
export const imageFilesValidator: Validator = (
|
|
rule,
|
|
value: OneOrArray<File>,
|
|
) => {
|
|
const files = castArray<File>(value);
|
|
const isValidImage = files.every((file: File) => isImageFile(file));
|
|
if (isValidImage) {
|
|
return Promise.resolve();
|
|
}
|
|
return Promise.reject(
|
|
new Error(
|
|
t`You are only allowed to upload ${IMAGE_EXTENSIONS.join(', ')} file.`,
|
|
),
|
|
);
|
|
};
|
|
|
|
export const imageOrZipFilesValidator: Validator = (
|
|
rule,
|
|
value: OneOrArray<File>,
|
|
) => {
|
|
const files = castArray<File>(value);
|
|
const isValidExtension = files.every((file: File) => {
|
|
return isImageFile(file) || isZipFile(file);
|
|
});
|
|
|
|
if (isValidExtension) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
return Promise.reject(
|
|
new Error(t`You are only allowed to upload image or .zip files.`),
|
|
);
|
|
};
|
|
|
|
export const sizeLimitImagesValidator: Validator = (
|
|
rule,
|
|
value: OneOrArray<File>,
|
|
) => {
|
|
const files = castArray(value);
|
|
if (files.every((file) => isFileUnderLimit(file, IMAGE_SIZE_LIMIT))) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
return Promise.reject(
|
|
new Error(
|
|
t`You are not allowed to upload image bigger than ${bytesToMegabytes(
|
|
IMAGE_SIZE_LIMIT,
|
|
)}MB.`,
|
|
),
|
|
);
|
|
};
|
|
|
|
export const sizeLimitFilesValidator: Validator = (
|
|
rule,
|
|
value: OneOrArray<File>,
|
|
) => {
|
|
const files = castArray(value);
|
|
if (files.every((file) => isFileUnderLimit(file))) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
return Promise.reject(
|
|
new Error(
|
|
t`You are not allowed to upload file bigger than ${bytesToMegabytes(
|
|
FILE_SIZE_LIMIT,
|
|
)}MB.`,
|
|
),
|
|
);
|
|
};
|
|
|
|
export const requiredFilesValidator: Validator = (
|
|
rule,
|
|
value: OneOrArray<File>,
|
|
) => {
|
|
const files = castArray(value);
|
|
if (files.length && value) {
|
|
return Promise.resolve();
|
|
}
|
|
|
|
return Promise.reject(
|
|
new Error(t`Please choose at least one file to upload.`),
|
|
);
|
|
};
|