File size: 2,009 Bytes
8d88d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import type { MessageFile } from "$lib/types/Message";
import { z } from "zod";

export interface FileProcessorOptions<TMimeType extends string = string> {
	supportedMimeTypes: TMimeType[];
	maxSizeInMB: number;
}

export type ImageProcessor<TMimeType extends string = string> = (file: MessageFile) => Promise<{
	file: Buffer;
	mime: TMimeType;
}>;

export const createDocumentProcessorOptionsValidator = <TMimeType extends string = string>(
	defaults: FileProcessorOptions<TMimeType>
) => {
	return z
		.object({
			supportedMimeTypes: z
				.array(
					z.enum<string, [TMimeType, ...TMimeType[]]>([
						defaults.supportedMimeTypes[0],
						...defaults.supportedMimeTypes.slice(1),
					])
				)
				.default(defaults.supportedMimeTypes),
			maxSizeInMB: z.number().positive().default(defaults.maxSizeInMB),
		})
		.default(defaults);
};

export type DocumentProcessor<TMimeType extends string = string> = (file: MessageFile) => {
	file: Buffer;
	mime: TMimeType;
};

export type AsyncDocumentProcessor<TMimeType extends string = string> = (
	file: MessageFile
) => Promise<{
	file: Buffer;
	mime: TMimeType;
}>;

export function makeDocumentProcessor<TMimeType extends string = string>(
	options: FileProcessorOptions<TMimeType>
): AsyncDocumentProcessor<TMimeType> {
	return async (file) => {
		const { supportedMimeTypes, maxSizeInMB } = options;
		const { mime, value } = file;

		const buffer = Buffer.from(value, "base64");
		const tooLargeInBytes = buffer.byteLength > maxSizeInMB * 1000 * 1000;

		if (tooLargeInBytes) {
			throw Error("Document is too large");
		}

		const outputMime = validateMimeType(supportedMimeTypes, mime);
		return { file: buffer, mime: outputMime };
	};
}

const validateMimeType = <T extends readonly string[]>(
	supportedMimes: T,
	mime: string
): T[number] => {
	if (!supportedMimes.includes(mime)) {
		const supportedMimesStr = supportedMimes.join(", ");

		throw Error(`Mimetype "${mime}" not found in supported mimes: ${supportedMimesStr}`);
	}

	return mime;
};