28 lines
1.2 KiB
TypeScript
Raw Normal View History

import Joi from "@stirling-tools/joi";
2023-11-27 23:35:18 +01:00
import { PdfFile } from "./PdfFile";
2023-12-28 01:56:01 +01:00
export const JoiPDFFileSchema = Joi.custom((value: Express.Multer.File[] /* <- also handles single files */ | PdfFile[] | PdfFile, helpers) => {
2023-12-21 22:52:05 +01:00
if (Array.isArray(value)) {
if(isPdfFileArray(value))
return value;
2023-12-21 22:52:05 +01:00
else { // File(s)
const firstWrongFile = value.find(f => f.mimetype != "application/pdf")
if(firstWrongFile)
throw new Error(`at least one of the files provided doesn't seem to be a PDF. Got the file ${JSON.stringify(firstWrongFile)} instead.`);
2023-12-21 22:52:05 +01:00
return PdfFile.fromMulterFiles(value);
}
}
else {
2023-12-21 22:52:05 +01:00
if (value instanceof PdfFile) {
return value;
}
else {
throw new Error("an invalid type (unhandeled, non-file-type) was provided to pdf validation process. Please report this to maintainers.");
2023-11-27 23:35:18 +01:00
}
}
}, "pdffile");
2023-12-21 22:52:05 +01:00
2023-12-28 02:26:25 +01:00
function isPdfFileArray(value: any[]): value is PdfFile[] { // "is" is a ts-typeguard - https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
2024-01-04 20:17:54 -05:00
return value.every((e) => e instanceof PdfFile);
}