Changed to promises and return the file stream on getting a raw file

This commit is contained in:
Lee 2022-11-15 03:34:29 +00:00
parent 9eca5f3b26
commit d335ec92ff
No known key found for this signature in database
GPG Key ID: 6EA25896ECCB3121

@ -52,7 +52,12 @@ export async function getFileInfo(fileId, isInternal = false) {
file.uploader = uploader; file.uploader = uploader;
file._id = undefined; file._id = undefined;
file.__v = undefined; file.__v = undefined;
file.fileUrl = process.env.NEXT_PUBLIC_SITE_URL + "/api/files/" + file.fileId; file.fileUrl =
process.env.NEXT_PUBLIC_SITE_URL +
"/api/files/" +
file.fileId +
"." +
file.ext;
return file; return file;
} }
@ -64,6 +69,7 @@ export async function getFileInfo(fileId, isInternal = false) {
* @param {Buffer} buffer The buffer of the file * @param {Buffer} buffer The buffer of the file
* @param {string} contentType The content type of the file * @param {string} contentType The content type of the file
* @param {Number} size The size of the file * @param {Number} size The size of the file
* @return The file id or undefined if there was an error
*/ */
export async function createFile( export async function createFile(
uploader, uploader,
@ -74,13 +80,13 @@ export async function createFile(
) { ) {
const fileId = randomString(process.env.FILE_ID_LENGTH); const fileId = randomString(process.env.FILE_ID_LENGTH);
const extention = fileName.split(".").at(-1).toLowerCase(); const extention = fileName.split(".").at(-1).toLowerCase();
// Todo: Check if the file was actually saved to return new Promise((resolve, reject) => {
// disk and create a return type so we can notify the user what happened createFileIO(
await createFileIO(
`${BASE_STORAGE}${uploader.uploadKey}`, `${BASE_STORAGE}${uploader.uploadKey}`,
`${fileId}.${extention}`, `${fileId}.${extention}`,
buffer buffer
); )
.then(async () => {
const file = await FileModel.create({ const file = await FileModel.create({
uploader: uploader._id, uploader: uploader._id,
fileId: fileId, fileId: fileId,
@ -103,7 +109,12 @@ export async function createFile(
} }
await file.save(); await file.save();
return `${fileId}.${extention}`; resolve(`${fileId}.${extention}`);
})
.catch((err) => {
reject();
});
});
} }
/** /**
@ -115,10 +126,10 @@ export async function createFile(
export async function getFileRaw(fileId) { export async function getFileRaw(fileId) {
const fileInfo = await getFileInfo(fileId, true); const fileInfo = await getFileInfo(fileId, true);
if (fileInfo == null) { if (fileInfo == null) {
return null; return { file: null, readStream: null };
} }
const filePath = `${BASE_STORAGE}${fileInfo.uploader.uploadKey}${path.sep}${fileInfo.fileId}.${fileInfo.ext}`; const filePath = `${BASE_STORAGE}${fileInfo.uploader.uploadKey}${path.sep}${fileInfo.fileId}.${fileInfo.ext}`;
const buffer = await readFileIO(filePath); const readStream = readFileIO(filePath);
return { file: fileInfo, buffer: buffer }; return { file: fileInfo, readStream: readStream };
} }