From 8686f0c27b33f39b92bfff69f4e6b819f9be218d Mon Sep 17 00:00:00 2001 From: Mathis Date: Mon, 14 Oct 2024 12:10:52 +0200 Subject: [PATCH] Add file deletion method in storage service Implemented a new method to delete files from the storage by checksum and extension. This method logs the deletion process and throws a NotFoundException if the file cannot be found. Updated dependencies to include 'rm' from 'node:fs/promises'. --- .../src/app/storage/storage.service.ts | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/backend/src/app/storage/storage.service.ts b/apps/backend/src/app/storage/storage.service.ts index cefc47a..f6bd2f4 100644 --- a/apps/backend/src/app/storage/storage.service.ts +++ b/apps/backend/src/app/storage/storage.service.ts @@ -1,6 +1,6 @@ import * as console from "node:console"; import * as crypto from "node:crypto"; -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, writeFile, rm } from "node:fs/promises"; import { join } from "node:path"; import { BadRequestException, @@ -263,4 +263,29 @@ export class StorageService { throw err; } } + + /** + * Deletes a file from the storage. + * + * @param {string} checksum - The checksum of the file to delete. + * @param {string} extension - The extension of the file to delete. + * @param {boolean} isDocumentation - A flag indicating whether the file is a documentation file. + * @return {Promise} A promise that resolves when the file is successfully deleted. + * @throws {NotFoundException} Throws an exception if the file cannot be found. + */ + public async delete( + checksum: string, + extension: string, + isDocumentation: boolean, + ) { + try { + const fileName = `${isDocumentation ? "doc" : "file"}-${checksum}.${extension.toLowerCase()}`; + console.log(`Deleting file "${fileName}" from storage...`); + await rm(join(process.cwd(), "assets/", fileName)); + console.log(`File "${fileName}" deleted successfully.`); + } catch (err) { + console.log("File not found."); + throw new NotFoundException(err); + } + } }