From 4d7ae970bc1179178330ce7ab73c765dfb8349bf Mon Sep 17 00:00:00 2001 From: Mathis Date: Mon, 30 Sep 2024 14:20:37 +0200 Subject: [PATCH] Add get method to FilesService Implemented a method to fetch a file and its information based on checksum. Integrated database and storage services to retrieve and prepare file stream and metadata. Also handles scenarios where the file is not found or multiple entries exist for the same checksum. --- apps/backend/src/app/files/files.service.ts | 63 ++++++++++++++++++++- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/apps/backend/src/app/files/files.service.ts b/apps/backend/src/app/files/files.service.ts index 8075ec8..4bcc90f 100644 --- a/apps/backend/src/app/files/files.service.ts +++ b/apps/backend/src/app/files/files.service.ts @@ -1,4 +1,63 @@ -import { Injectable } from "@nestjs/common"; +import { Injectable, NotFoundException, StreamableFile } from "@nestjs/common"; +import { DbService } from "apps/backend/src/app/db/db.service"; +import { FilesTable } from "apps/backend/src/app/db/schema"; +import { StorageService } from "apps/backend/src/app/storage/storage.service"; +import { IFileWithInformation } from "apps/backend/src/app/storage/storage.types"; +import { eq } from "drizzle-orm"; @Injectable() -export class FilesService {} +export class FilesService { + constructor( + private readonly storage: StorageService, + private readonly database: DbService, + ) {} + + /** + * Fetches a file and its information based on the provided checksum. + * + * @param {string} checksum - The unique identifier for the file. + * @return {Promise>} An object containing the stream of the file, its information, and additional data. + * @throws {NotFoundException} If the file with the given checksum is not found. + */ + public async get(checksum: string): Promise> { + const foundFiles = await this.database + .use() + .select() + .from(FilesTable) + .where(eq(FilesTable.checksum, checksum)) + .prepare("getFileFromChecksum") + .execute(); + + if (foundFiles.length === 0) + throw new NotFoundException("File with checksum not found", { + description: `checksum : ${checksum}` + }); + + if (foundFiles.length > 1) + console.log( + "Multiples entries found in the database.\nInformation from the first row will be used.", + ); + const file = foundFiles[0]; + + const fileBuffer = await this.storage.read( + file.checksum, + file.extension, + file.isDocumentation, + ); + const streamableFile = new StreamableFile(fileBuffer); + const fileInformation = await this.storage.generateInformation( + fileBuffer, + file.fileName, + file.isDocumentation, + ); + + return { + stream: streamableFile, + info: fileInformation, + additionalData: { + //Since we can have twice or more entry in the database for the same checksum of a file. + foundEntry: foundFiles.length, + }, + }; + } +}