monkeytype/backend/dao/result.js

73 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-07-10 01:27:08 +08:00
const { ObjectID } = require("mongodb");
2021-06-09 01:37:42 +08:00
const MonkeyError = require("../handlers/error");
const { mongoDB } = require("../init/mongodb");
const UserDAO = require("./user");
2021-06-09 01:37:42 +08:00
class ResultDAO {
static async addResult(uid, result) {
2021-06-13 02:02:19 +08:00
let user;
2021-07-06 22:22:05 +08:00
try {
2021-06-13 02:02:19 +08:00
user = await UserDAO.getUser(uid);
2021-07-06 22:22:05 +08:00
} catch (e) {
2021-06-13 02:02:19 +08:00
user = null;
}
2021-08-18 08:41:29 +08:00
if (!user) throw new MonkeyError(404, "User not found", "add result");
2021-06-09 01:37:42 +08:00
if (result.uid === undefined) result.uid = uid;
result.ir = true;
2021-07-09 23:32:57 +08:00
let res = await mongoDB().collection("results").insertOne(result);
return {
insertedId: res.insertedId,
};
2021-06-09 01:37:42 +08:00
}
static async deleteAll(uid) {
return await mongoDB().collection("results").deleteMany({ uid });
}
2021-07-10 01:27:08 +08:00
static async updateTags(uid, resultid, tags) {
const result = await mongoDB()
.collection("results")
.findOne({ _id: ObjectID(resultid), uid });
2021-06-09 01:37:42 +08:00
if (!result) throw new MonkeyError(404, "Result not found");
const userTags = await UserDAO.getTags(uid);
2021-07-10 01:27:08 +08:00
const userTagIds = userTags.map((tag) => tag._id.toString());
let validTags = true;
2021-07-06 22:22:05 +08:00
tags.forEach((tagId) => {
2021-07-10 01:27:08 +08:00
if (!userTagIds.includes(tagId)) validTags = false;
});
2021-07-06 22:22:05 +08:00
if (!validTags)
throw new MonkeyError(400, "One of the tag id's is not vaild");
2021-06-09 01:37:42 +08:00
return await mongoDB()
.collection("results")
2021-07-10 01:27:08 +08:00
.updateOne({ _id: ObjectID(resultid), uid }, { $set: { tags } });
2021-06-09 01:37:42 +08:00
}
static async getResult(uid, id) {
const result = await mongoDB()
.collection("results")
.findOne({ _id: ObjectID(id), uid });
2021-06-09 01:37:42 +08:00
if (!result) throw new MonkeyError(404, "Result not found");
return result;
}
static async getResultByTimestamp(uid, timestamp) {
return await mongoDB().collection("results").findOne({ uid, timestamp });
}
2021-06-09 01:37:42 +08:00
static async getResults(uid, start, end) {
start = start ?? 0;
end = end ?? 1000;
const result = await mongoDB()
2021-07-07 21:04:28 +08:00
.collection("results")
.find({ uid })
2021-08-04 21:37:15 +08:00
.sort({ timestamp: -1 })
2021-06-09 01:37:42 +08:00
.skip(start)
2021-07-06 22:22:05 +08:00
.limit(end)
.toArray(); // this needs to be changed to later take patreon into consideration
2021-06-09 01:37:42 +08:00
if (!result) throw new MonkeyError(404, "Result not found");
return result;
}
}
module.exports = ResultDAO;