Skip to content

Commit

Permalink
Implement dedicated interceptor for multiple file upload (#273)
Browse files Browse the repository at this point in the history
  • Loading branch information
hood committed Oct 28, 2020
1 parent 50e8c7f commit 69e46e2
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
45 changes: 45 additions & 0 deletions lib/gcloud-storage-files.interceptor.ts
Original file line number Diff line number Diff line change
@@ -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<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
@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<Observable<any>> {
(await this.interceptor.intercept(context, next)) as Observable<any>;

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<NestInterceptor>;
}
1 change: 1 addition & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

0 comments on commit 69e46e2

Please sign in to comment.