Added File uploads and fetching of said files

This commit is contained in:
2025-12-22 13:03:14 +01:00
parent ba6d8eeffc
commit 273314739f
10 changed files with 354 additions and 35 deletions

91
src/cdn.js Normal file
View File

@@ -0,0 +1,91 @@
import { rmSync } from 'fs';
import { copyFile, mkdir } from 'fs/promises';
import { Collection, Db, ObjectId } from 'mongodb';
import multer from 'multer';
const dataPath = process.env.JEOPARDY_CDN_DATA_PATH;
const upload = multer({ dest: dataPath });
/**
* @type {Collection}
*/
let ressources;
/**
*
* @param {*} app
* @param {Db} db
*/
export function initCdn(app, db) {
ressources = db.collection('ressources');
app.post('/upload', upload.single('file'), uploadFile);
app.get('/cdn/:userid/:resid', fetchFile);
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
function uploadFile(req, res, next) {
console.log(req.file, req.body);
/**
* @type {string | undefined}
*/
const path = req.body.path;
if (path !== undefined && path.startsWith('/') && !path.includes('.')) {
let destinationPath = `${dataPath}/${req.user._id}${req.body.path}`;
mkdir(destinationPath, {
recursive: true,
})
.then(() => {
return copyFile(
req.file.path,
`${destinationPath}/${req.file.filename}`,
);
})
.then(async () => {
rmSync(req.file.path);
await ressources.insertOne({
fullpath: destinationPath,
path: path,
user: req.user._id,
mimetype: req.file.mimetype,
name: req.file.originalname,
filename: req.file.filename,
});
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
rmSync(req.file.path);
res.sendStatus(500);
});
} else {
rmSync(req.file.path);
res.sendStatus(400);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchFile(req, res) {
let ressource = await ressources.findOne({
user: new ObjectId(req.params.userid),
filename: req.params.resid,
});
if (ressource) {
res.sendFile(ressource.fullpath + ressource.filename);
} else {
res.sendStatus(404);
}
}