From 69e46e26b9cdc0b599e85cbefe307ec575bc48bd Mon Sep 17 00:00:00 2001 From: Andrea Cappuccio Date: Wed, 28 Oct 2020 03:42:05 +0100 Subject: [PATCH] Implement dedicated interceptor for multiple file upload (#273) --- lib/gcloud-storage-files.interceptor.ts | 45 +++++++++++++++++++++++++ lib/index.ts | 1 + 2 files changed, 46 insertions(+) create mode 100644 lib/gcloud-storage-files.interceptor.ts diff --git a/lib/gcloud-storage-files.interceptor.ts b/lib/gcloud-storage-files.interceptor.ts new file mode 100644 index 0000000..b4deee0 --- /dev/null +++ b/lib/gcloud-storage-files.interceptor.ts @@ -0,0 +1,45 @@ +import { CallHandler, ExecutionContext, Injectable, Logger, mixin, NestInterceptor, Type } from '@nestjs/common'; +import { FilesInterceptor } from '@nestjs/platform-express'; +import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface'; +import { Observable } from 'rxjs'; + +import { GCloudStoragePerRequestOptions } from './gcloud-storage.interface'; +import { GCloudStorageService } from './gcloud-storage.service'; + +export function GCloudStorageFilesInterceptor( + fieldName: string, + localOptions?: MulterOptions, + gcloudStorageOptions?: Partial, +): Type { + @Injectable() + class MixinInterceptor implements NestInterceptor { + public interceptor: NestInterceptor; + + constructor(private readonly gcloudStorage: GCloudStorageService) { + this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))(); + } + + async intercept(context: ExecutionContext, next: CallHandler): Promise> { + (await this.interceptor.intercept(context, next)) as Observable; + + const request = context.switchToHttp().getRequest(); + + const files = request[fieldName]; + + if (!files.length) { + Logger.error( + 'GCloudStorageFilesInterceptor', + `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`, + ); + return; + } + + for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions); + + return next.handle(); + } + } + + const Interceptor = mixin(MixinInterceptor); + return Interceptor as Type; +} diff --git a/lib/index.ts b/lib/index.ts index 9234515..e9c3a1a 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -4,3 +4,4 @@ export * from './gcloud-storage.interface'; export * from './gcloud-storage.module'; export * from './gcloud-storage.service'; export * from './gcloud-stroage-file.interceptor'; +export * from './gcloud-storage-files.interceptor';