Skip to content

Instantly share code, notes, and snippets.

@Insidexa
Created September 10, 2019 08:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Insidexa/362d64f90e9330f7a71e0e03cf2999a3 to your computer and use it in GitHub Desktop.
Save Insidexa/362d64f90e9330f7a71e0e03cf2999a3 to your computer and use it in GitHub Desktop.
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class ExampleUploadInterceptor extends MulterInterceptor implements NestInterceptor {
private MAX_FILE_SIZE = 50 * 1024 * 1024;
constructor(
private fs: FsService,
) {
super();
}
public async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
return await super.intercept(context, next, {
fieldName: 'uploadField',
uploadConfig: this.fs.multerConfig({
dest: 'example-folder',
filenameGenerator: getFileName,
limits: {
fileSize: this.MAX_FILE_SIZE,
},
fileFilter: (req, file: MulterLocalFile, cb) => {
const mimes = extensions.map(ext => ext.mime);
if (mimes.includes(file.mimetype) === false) {
cb(new MimetypeNotSupportedException());
}
cb(null, true);
},
}),
});
}
}
import { CallHandler, ExecutionContext } from '@nestjs/common';
import { Dictionary } from '../../../common/interfaces/dictionary';
import { Observable } from 'rxjs';
import * as multer from 'multer';
import { transformException } from '@nestjs/platform-express/multer/multer/multer.utils';
export class MulterInterceptor {
public async intercept(
context: ExecutionContext,
next: CallHandler,
options: { fieldName: string, uploadConfig: Dictionary },
): Promise<Observable<any>> {
const { fieldName, uploadConfig } = options;
const ctx = context.switchToHttp();
const multerInstance = (multer as any)(uploadConfig);
await new Promise((resolve, reject) =>
multerInstance.single(fieldName)(
ctx.getRequest(),
ctx.getResponse(),
(err: any) => {
if (err) {
const error = transformException(err);
return reject(error);
}
resolve();
},
),
);
return next.handle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment