From 18a59993343ff7ba94b132c3213e79526c579551 Mon Sep 17 00:00:00 2001 From: Mathis Date: Tue, 15 Oct 2024 14:09:15 +0200 Subject: [PATCH] Implement file type removal functionality Add logic to remove file types by ID, ensuring they are not in use by any files or machines. Handle errors appropriately, throwing specific exceptions for cases where the file type cannot be deleted or an internal error occurs. --- apps/backend/src/app/files/files.service.ts | 51 ++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/apps/backend/src/app/files/files.service.ts b/apps/backend/src/app/files/files.service.ts index 68aa367..f567a78 100644 --- a/apps/backend/src/app/files/files.service.ts +++ b/apps/backend/src/app/files/files.service.ts @@ -294,7 +294,54 @@ export class FilesService { .execute(); } - public async removeFileType() { - //TODO + /** + * Removes a file type by its ID if it is not in use by any files or machines. + * + * @param {string} fileTypeId - The ID of the file type to be removed. + * @return {Promise} - A promise that resolves to the result of the deletion operation. + * @throws {BadRequestException} - If the file type is in use by any files or machines. + * @throws {InternalServerErrorException} - If an error occurs during the deletion process. + */ + public async removeFileType(fileTypeId: string): Promise { + const fileUsingFileType = await this.database + .use() + .select() + .from(FilesTable) + .where(eq(FilesTable.fileType, fileTypeId)) + .prepare("checkFileTypeInUseInFiles") + .execute(); + + if (fileUsingFileType.length > 0) { + throw new BadRequestException( + "This file type is in use by some files and cannot be deleted.", + ); + } + const machinesUsingFileType = await this.database + .use() + .select() + .from(FilesTypeForMachine) + .where(eq(FilesTypeForMachine.fileTypeId, fileTypeId)) + .prepare("getMachineByFileTypeId") + .execute(); + + if (machinesUsingFileType.length > 0) { + throw new BadRequestException( + "This file type is in use by some machines and cannot be deleted until there is no machine using this fileType.", + ); + } + + try { + return await this.database + .use() + .delete(FilesTypesTable) + .where(eq(FilesTypesTable.id, fileTypeId)) + .returning() + .prepare("deleteFileTypeById") + .execute(); + } catch (e) { + throw new InternalServerErrorException( + "An error occurred while deleting a file type", + ); + } } }