monkeytype/backend/dao/preset.js

55 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-06-09 01:27:51 +08:00
const MonkeyError = require("../handlers/error");
const { mongoDB } = require("../init/mongodb");
2021-07-09 22:50:15 +08:00
const { ObjectID } = require("mongodb");
2021-06-09 01:27:51 +08:00
class PresetDAO {
2021-07-09 06:28:00 +08:00
static async getPresets(uid) {
const preset = await mongoDB()
.collection("presets")
.find({ uid })
.sort({ timestamp: -1 })
.toArray(); // this needs to be changed to later take patreon into consideration
return preset;
}
2021-06-09 01:27:51 +08:00
static async addPreset(uid, name, config) {
const count = await mongoDB().collection("presets").find({ uid }).count();
if (count >= 10) throw new MonkeyError(409, "Too many presets");
2021-07-09 22:50:15 +08:00
let preset = await mongoDB()
2021-07-09 21:41:55 +08:00
.collection("presets")
2021-07-09 22:50:15 +08:00
.insertOne({ uid, name, config });
2021-07-09 06:28:00 +08:00
return {
2021-07-09 22:50:15 +08:00
insertedId: preset.insertedId,
2021-07-09 06:28:00 +08:00
};
2021-06-09 01:27:51 +08:00
}
2021-07-09 22:50:15 +08:00
static async editPreset(uid, _id, name, config) {
console.log(_id);
const preset = await mongoDB()
.collection("presets")
.findOne({ uid, _id: ObjectID(_id) });
2021-06-09 01:27:51 +08:00
if (!preset) throw new MonkeyError(404, "Preset not found");
2021-07-09 06:28:00 +08:00
if (config) {
return await mongoDB()
.collection("presets")
2021-07-09 22:50:15 +08:00
.updateOne({ uid, _id: ObjectID(_id) }, { $set: { name, config } });
2021-07-09 06:28:00 +08:00
} else {
return await mongoDB()
.collection("presets")
2021-07-09 22:50:15 +08:00
.updateOne({ uid, _id: ObjectID(_id) }, { $set: { name } });
2021-07-09 06:28:00 +08:00
}
2021-06-09 01:27:51 +08:00
}
2021-07-09 22:50:15 +08:00
static async removePreset(uid, _id) {
2021-07-09 21:41:55 +08:00
const preset = await mongoDB()
.collection("presets")
2021-07-09 22:50:15 +08:00
.findOne({ uid, _id: ObjectID(_id) });
2021-06-09 01:27:51 +08:00
if (!preset) throw new MonkeyError(404, "Preset not found");
2021-07-09 22:50:15 +08:00
return await mongoDB()
.collection("presets")
.deleteOne({ uid, _id: ObjectID(_id) });
2021-06-09 01:27:51 +08:00
}
}
module.exports = PresetDAO;