From 8e662167dc30fb82dbaf42fe7285b0a19808d995 Mon Sep 17 00:00:00 2001 From: David Mehren Date: Sat, 17 Oct 2020 18:50:53 +0200 Subject: [PATCH] MediaService: Improve error handling and logging Add debug logging to `saveFile` method and throw the proper errors when problems with the mime type are encountered Signed-off-by: David Mehren --- src/media/media.service.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/media/media.service.ts b/src/media/media.service.ts index 3beec6f42..c9fc6ccd9 100644 --- a/src/media/media.service.ts +++ b/src/media/media.service.ts @@ -3,6 +3,8 @@ import { ModuleRef } from '@nestjs/core'; import { InjectRepository } from '@nestjs/typeorm'; import * as FileType from 'file-type'; import { Repository } from 'typeorm'; +import { ClientError } from '../errors/errors'; +import { ConsoleLoggerService } from '../logger/console-logger.service'; import { NotesService } from '../notes/notes.service'; import { UsersService } from '../users/users.service'; import { BackendType } from './backends/backend-type.enum'; @@ -13,22 +15,34 @@ import { MulterFile } from './multer-file.interface'; @Injectable() export class MediaService { constructor( + private readonly logger: ConsoleLoggerService, @InjectRepository(MediaUpload) private mediaUploadRepository: Repository, private notesService: NotesService, private usersService: UsersService, private moduleRef: ModuleRef, - ) {} + ) { + this.logger.setContext(MediaService.name); + } + + private static isAllowedMimeType(mimeType: string): boolean { + //TODO: Which mimetypes are allowed? + return true; + } public async saveFile(file: MulterFile, username: string, noteId: string) { + this.logger.debug( + `Saving '${file.originalname}' for note '${noteId}' and user '${username}'`, + 'saveFile', + ); const note = await this.notesService.getNoteByIdOrAlias(noteId); const user = await this.usersService.getUserByUsername(username); const fileTypeResult = await FileType.fromBuffer(file.buffer); if (!fileTypeResult) { - throw new Error('Could not detect file type.'); + throw new ClientError('Could not detect file type.'); } if (!MediaService.isAllowedMimeType(fileTypeResult.mime)) { - throw new Error('MIME type not allowed'); + throw new ClientError('MIME type not allowed.'); } //TODO: Choose backend according to config const mediaUpload = MediaUpload.create( @@ -37,6 +51,7 @@ export class MediaService { fileTypeResult.ext, BackendType.FILEYSTEM, ); + this.logger.debug(`Generated filename: '${mediaUpload.id}'`, 'saveFile'); const backend = this.moduleRef.get(FilesystemBackend); const [url, backendData] = await backend.saveFile( file.buffer, @@ -46,9 +61,4 @@ export class MediaService { await this.mediaUploadRepository.save(mediaUpload); return url; } - - private static isAllowedMimeType(mimeType: string): boolean { - //TODO: Which mimetypes are allowed? - return true; - } }