Created
September 10, 2019 08:24
-
-
Save Insidexa/362d64f90e9330f7a71e0e03cf2999a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}, | |
}), | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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