Skip to content

Commit

Permalink
feat: move grid fs calls from db server to db helper[3966]
Browse files Browse the repository at this point in the history
  • Loading branch information
Ihar committed Aug 19, 2024
1 parent fbaa21b commit 924763a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 23 deletions.
27 changes: 4 additions & 23 deletions common/src/database-modules/database-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3543,40 +3543,21 @@ export class DatabaseServer {
* Save file
* @param uuid
* @param buffer
*
* @returns file ID
*/
public static async saveFile(uuid: string, buffer: Buffer): Promise<ObjectId> {
return new Promise<ObjectId>((resolve, reject) => {
try {
const fileStream = DataBaseHelper.gridFS.openUploadStream(uuid);
fileStream.write(buffer);
fileStream.end(() => {
resolve(fileStream.id);
});
} catch (error) {
reject(error);
}
});
return DataBaseHelper.saveFile(uuid, buffer)
}

/**
* Save file
* Load file
* @param id
*
* @returns file ID
*/
public static async loadFile(id: ObjectId): Promise<Buffer> {
const files = await DataBaseHelper.gridFS.find(id).toArray();
if (files.length === 0) {
return null;
}
const file = files[0];
const fileStream = DataBaseHelper.gridFS.openDownloadStream(file._id);
const bufferArray = [];
for await (const data of fileStream) {
bufferArray.push(data);
}
return Buffer.concat(bufferArray);
return DataBaseHelper.loadFile(id)
}

/**
Expand Down
40 changes: 40 additions & 0 deletions common/src/helpers/db-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,46 @@ export class DataBaseHelper<T extends BaseEntity> {
return DataBaseHelper._gridFS;
}

/**
* Save file
* @param uuid
* @param buffer
* @returns file ID
*/
public static async saveFile(uuid: string, buffer: Buffer): Promise<ObjectId> {
return new Promise<ObjectId>((resolve, reject) => {
try {
const fileStream = DataBaseHelper.gridFS.openUploadStream(uuid);
fileStream.write(buffer);
fileStream.end(() => {
resolve(fileStream.id);
});
} catch (error) {
reject(error);
}
});
}

/**
* Load file
* @param id
*
* @returns file ID
*/
public static async loadFile(id: ObjectId): Promise<Buffer> {
const files = await DataBaseHelper.gridFS.find(id).toArray();
if (files.length === 0) {
return null;
}
const file = files[0];
const fileStream = DataBaseHelper.gridFS.openDownloadStream(file._id);
const bufferArray = [];
for await (const data of fileStream) {
bufferArray.push(data);
}
return Buffer.concat(bufferArray);
}

/**
* Delete entities by filters
* @param filters filters
Expand Down

0 comments on commit 924763a

Please sign in to comment.