/
test.js
93 lines (75 loc) · 2.32 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import mongoose from "mongoose";
import TestModel from "../../models/TestModel.js";
import QuestionModel from "../../models/QuestionModel.js";
import {
getQuestionDetail,
getQuestionsByTests,
handleDeleteManyQuestions
} from "./question.js";
const checkExistedTestId = async (testId) => {
const isExisted = await TestModel.exists({
_id: new mongoose.Types.ObjectId(testId)
}).lean();
return Boolean(isExisted);
};
const createNewTest = async (test) => {
const newTest = await TestModel.create(test);
return newTest;
};
const updateExistedTest = async (testId, testInfo) => {
const updatedTest = await TestModel.findOneAndUpdate(
{ _id: testId },
testInfo
).lean();
return updatedTest;
};
const getTestDetail = async (testId) => {
const [test, questions] = await Promise.all([
TestModel.findOne(
{ _id: testId },
{ _id: true, timeLimit: true, score: true, created: true }
).lean(),
QuestionModel.find({ testId }, { _id: true })
]);
const promiseQuestionDetails = questions.map((_id) => {
return getQuestionDetail(_id);
});
const questionDetails = await Promise.all(promiseQuestionDetails);
return { ...test, questions: questionDetails };
};
const getTestsByLesson = async (lessonId) => {
const [count, listTests] = await Promise.all([
TestModel.find({ lessonId }).count(),
TestModel.find({ lessonId }, { _id: true }).lean()
]);
const listPromiseTestDetails = listTests.map((_id) => {
return getTestDetail(_id);
});
const listTestDetails = await Promise.all(listPromiseTestDetails);
const output = { count, tests: listTestDetails };
return output;
};
const deleteTestsByIds = async (testIds) => {
const output = await TestModel.deleteMany({
_id: { $in: testIds }
}).lean();
return output;
};
const handleDeleteTests = async (testIds) => {
const listQuestions = await getQuestionsByTests(testIds);
const listQuestionIds = listQuestions.map((question) => question._id);
const [deleteTest, deleteQuestion] = await Promise.all([
deleteTestsByIds(testIds),
handleDeleteManyQuestions(listQuestionIds)
]);
const isDeleted = Boolean(deleteTest.deletedCount) && Boolean(deleteQuestion);
return isDeleted;
};
export {
checkExistedTestId,
createNewTest,
updateExistedTest,
getTestDetail,
getTestsByLesson,
handleDeleteTests
};