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.
This commit is contained in:
parent
ddf9ef4860
commit
4d7ae970bc
@ -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<IFileWithInformation<object>>} 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<IFileWithInformation<object>> {
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user