forked from Blazity/nest-file-fastify
-
Notifications
You must be signed in to change notification settings - Fork 3
/
file-fields.ts
92 lines (76 loc) · 2.32 KB
/
file-fields.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { BadRequestException } from "@nestjs/common";
import { FastifyRequest } from "fastify";
import { UploadOptions } from "../options";
import { StorageFile } from "../../storage/storage";
import { getParts } from "../request";
import { removeStorageFiles } from "../file";
import { filterUpload } from "../filter";
import { MultipartFile } from "@fastify/multipart";
export interface UploadField {
/**
* Field name
*/
name: string;
/**
* Max number of files in this field
*/
maxCount?: number;
}
export type UploadFieldMapEntry = Required<Pick<UploadField, "maxCount">>;
export const uploadFieldsToMap = (uploadFields: UploadField[]) => {
const map = new Map<string, UploadFieldMapEntry>();
uploadFields.forEach(({ name, ...opts }) => {
map.set(name, { maxCount: 1, ...opts });
});
return map;
};
export const handleMultipartFileFields = async (
req: FastifyRequest,
fieldsMap: Map<string, UploadFieldMapEntry>,
options: UploadOptions,
) => {
const parts = getParts(req, options);
const body: Record<string, any> = {};
const files: Record<string, StorageFile[]> = {};
const removeFiles = async (error?: boolean) => {
const allFiles = ([] as StorageFile[]).concat(...Object.values(files));
return await removeStorageFiles(options.storage!, allFiles, error);
};
try {
for await (const part of parts) {
if (part.file) {
const fieldOptions = fieldsMap.get(part.fieldname);
if (fieldOptions == null) {
throw new BadRequestException(
`Field ${part.fieldname} doesn't accept files`,
);
}
if (files[part.fieldname] == null) {
files[part.fieldname] = [];
}
if (files[part.fieldname].length + 1 > fieldOptions.maxCount) {
throw new BadRequestException(
`Field ${part.fieldname} accepts max ${fieldOptions.maxCount} files`,
);
}
const file = await options.storage!.handleFile(
part as MultipartFile,
req,
);
if (await filterUpload(options, req, file)) {
files[part.fieldname].push(file);
}
} else {
body[part.fieldname] = part.value;
}
}
} catch (error) {
await removeFiles(true);
throw error;
}
return {
body,
files,
remove: () => removeFiles(),
};
};