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