monkeytype/backend/dao/usersDAO.js

28 lines
838 B
JavaScript
Raw Normal View History

2021-06-07 01:26:12 +08:00
const MonkeyError = require("../handlers/error");
2021-06-07 00:32:37 +08:00
const { mongoDB } = require("../init/mongodb");
class UsersDAO {
static async addUser(name, email, uid) {
return await mongoDB()
.collection("users")
.insertOne({ name, email, uid, addedAt: Date.now() });
}
static async updateName(uid, name) {
const nameDoc = await mongoDB()
.collection("users")
.findOne({ name: { $regex: new RegExp(`^${name}$`, "i") } });
2021-06-07 01:26:12 +08:00
if (nameDoc) throw new MonkeyError(409, "Username already taken");
2021-06-07 00:32:37 +08:00
return await mongoDB()
.collection("users")
.updateOne({ uid }, { $set: { name } });
}
static async getUser(uid) {
const user = await mongoDB().collection("users").findOne({ uid });
2021-06-07 01:26:12 +08:00
if (!user) throw new MonkeyError(404, "User not found");
2021-06-07 00:32:37 +08:00
return user;
}
}
module.exports = UsersDAO;