-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy pathfile-fields.interceptor.ts
53 lines (49 loc) · 1.33 KB
/
file-fields.interceptor.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
import {
CallHandler,
ExecutionContext,
Inject,
mixin,
NestInterceptor,
Optional,
Type,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { MULTIPART_MODULE_OPTIONS } from '../files.constants';
import {
MultipartOptions,
UploadField,
} from '../interfaces/multipart-options.interface';
import { MultipartWrapper, transformException } from '../multipart';
export const FileFieldsInterceptor = (
uploadFields: UploadField[],
localOptions?: MultipartOptions,
): Type<NestInterceptor> => {
class MixinInterceptor implements NestInterceptor {
protected multipart: MultipartWrapper;
public constructor(
@Optional()
@Inject(MULTIPART_MODULE_OPTIONS)
options: MultipartOptions = {},
) {
this.multipart = new MultipartWrapper({
...options,
...localOptions,
});
}
public async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
const req = context.switchToHttp().getRequest();
const fieldname = 'files';
try {
req[fieldname] = await this.multipart.fileFields(uploadFields)(req);
} catch (err) {
throw transformException(err);
}
return next.handle();
}
}
const Interceptor = mixin(MixinInterceptor);
return Interceptor as Type<NestInterceptor>;
};