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", + ); + } } }