Added Editing of Questions

This commit is contained in:
2026-01-02 18:01:02 +01:00
parent 832ff99a7b
commit ba96584300
3 changed files with 153 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
import { Collection, Db, ObjectId } from 'mongodb';
import { checkStringProp } from './util.js';
import { checkNumberProp, checkObjectProp, checkStringProp } from './util.js';
/**
* @type {Collection}
@@ -95,6 +95,7 @@ export function initGames(app, db) {
app.post('/category/rename', renameCategory);
app.get('/question', fetchQuestion);
app.post('/question', updateQuestion);
}
/**
@@ -592,6 +593,104 @@ async function deleteWallRoute(req, res) {
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function updateQuestion(req, res) {
if (
!checkStringProp(req.body, '_id') &&
!checkStringProp(req.body, 'owner') &&
!checkStringProp(req.body, 'type') &&
!checkNumberProp(req.body, 'points') &&
!checkObjectProp(req.body, 'data')
) {
res.sendStatus(400);
return;
}
if (req.body.owner !== req.user._id.toString()) {
res.sendStatus(403);
return;
}
/**
* @type {string}
*/
let _id = req.body._id;
let replacement;
if (
req.body.type === QuestionType.SIMPLE ||
req.body.type === QuestionType.MULTIPLE_CHOICE
) {
replacement = toNormalQuestion(req.body);
} else if (
req.body.type === QuestionType.IMAGE ||
req.body.type === QuestionType.IMAGE_MULTIPLE_CHOICE
) {
replacement = toImageQuestion(req.body);
} else if (
req.body.type === QuestionType.AUDIO ||
req.body.type === QuestionType.AUDIO_MULTIPLE_CHOICE
) {
replacement = toAudioQuestion(req.body);
}
cQuestions
.replaceOne(
{
_id: new ObjectId(_id),
owner: req.user._id,
},
replacement,
)
.then((result) => {
if (result.modifiedCount === 1) {
res.sendStatus(200);
} else res.sendStatus(500);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
function toNormalQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
};
}
function toImageQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
data: {
...body.data,
image:
body.data.image === null ? null : new ObjectId(body.data.image),
},
};
}
function toAudioQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
data: {
...body.data,
audio:
body.data.audio === null ? null : new ObjectId(body.data.audio),
},
};
}
/**
*
* @param {ObjectId} _id