From b29b188912ed49e16b1994ca266c68cfe11ee23b Mon Sep 17 00:00:00 2001 From: Mathis Date: Tue, 15 Oct 2024 13:47:11 +0200 Subject: [PATCH] Add createFileType method and DTO validations Introduced createFileType method to handle file type creation, including format validation and error handling for database operations. Updated CreateFileTypeDto with length constraints on name and mime properties. --- apps/backend/src/app/files/files.dto.ts | 8 +++- apps/backend/src/app/files/files.service.ts | 41 +++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/apps/backend/src/app/files/files.dto.ts b/apps/backend/src/app/files/files.dto.ts index 9fa652a..f5f60a6 100644 --- a/apps/backend/src/app/files/files.dto.ts +++ b/apps/backend/src/app/files/files.dto.ts @@ -18,5 +18,11 @@ export class CreateFilesDto { } export class CreateFileTypeDto { - //TODO + @MaxLength(128) + @MinLength(3) + name: string; + + @MaxLength(64) + @MinLength(4) + mime: string; } diff --git a/apps/backend/src/app/files/files.service.ts b/apps/backend/src/app/files/files.service.ts index 08bcbac..d3920cb 100644 --- a/apps/backend/src/app/files/files.service.ts +++ b/apps/backend/src/app/files/files.service.ts @@ -1,4 +1,5 @@ import { + BadRequestException, Injectable, InternalServerErrorException, NotFoundException, @@ -246,4 +247,44 @@ export class FilesService { } return inserted[0]; } + + /** + * Creates a new file type in the database. + * + * @param {string} name - The name of the file type. + * @param {string} mime - The MIME type for the file type, expected in `type/subtype` format. + * @return {Promise} A promise that resolves to the created file type object. + * @throws {BadRequestException} If the MIME type format is invalid. + * @throws {InternalServerErrorException} If an error occurs during the database operation. + */ + public async createFileType(name: string, mime: string) { + if (!/^[\w-]+\/[\w-]+$/.test(mime)) { + throw new BadRequestException("Invalid MIME type format"); + } + try { + return await this.database + .use() + .insert(FilesTypesTable) + .values({ + typeName: name, + mime: mime, + }) + .returning() + .prepare("createFileType") + .execute(); + } catch (e) { + console.error(e); + throw new InternalServerErrorException( + "An error occured while creating the file type", + ); + } + } + + public async getAllFilesTypes() { + //TODO + } + + public async removeFileType() { + //TODO + } }