/
MultipartFileMiddleware.ts
46 lines (37 loc) · 1.26 KB
/
MultipartFileMiddleware.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
import {Configuration, EndpointInfo, IMiddleware, Middleware, Req, Res} from "@tsed/common";
import * as multer from "multer";
import {BadRequest} from "@tsed/exceptions";
import {promisify} from "util";
/**
* @middleware
*/
@Middleware()
export class MultipartFileMiddleware implements IMiddleware {
private multer: any = multer;
constructor(@Configuration() private configuration: Configuration) {}
async use(@EndpointInfo() endpoint: EndpointInfo, @Req() request: Req, @Res() response: Res) {
try {
const endpointConfiguration = endpoint.get(MultipartFileMiddleware);
return await promisify(this.invoke(endpointConfiguration))(request, response);
} catch (er) {
throw er.code ? new BadRequest(`${er.message} ${er.field || ""}`.trim()) : er;
}
}
invoke(conf: any) {
const dest = this.configuration.uploadDir;
const options = {
dest,
...(this.configuration.get<any>("multer") || {}),
...(conf.options || {})
};
/* istanbul ignore next */
if (options.storage) {
delete options.dest;
}
if (!conf.any) {
const fields = conf.fields.map(({name, maxCount}: any) => ({name, maxCount}));
return this.multer(options).fields(fields);
}
return this.multer(options).any();
}
}