akf-forum/classes/user.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

2022-04-06 21:14:46 +03:00
const { UserModel } = require("../models");
2022-03-13 16:16:46 +03:00
module.exports = class User {
2022-04-06 21:14:46 +03:00
constructor(name = "guest", avatar = "/images/guest.png", time = Date.now(), admin = false, deleted = false) {
2022-03-13 16:16:46 +03:00
this.name = name;
this.avatar = avatar;
this.time = time;
this.admin = admin;
2022-03-13 17:12:09 +03:00
this.deleted = deleted;
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
async getById(id = this.id) {
2022-04-06 22:21:50 +03:00
try {
this.id = Number(id);
const user = await UserModel.findOne({ id });
if (!user) return null;
const { name = "guest", avatar = "/images/guest.png", time = Date.now(), admin = false, deleted = false } = user;
this.name = name;
this.avatar = avatar;
this.time = time;
this.admin = admin;
this.deleted = deleted;
return this;
} catch (e) {
return null;
}
2022-03-13 17:12:09 +03:00
2022-04-06 21:14:46 +03:00
}
2022-03-13 17:12:09 +03:00
2022-04-06 21:14:46 +03:00
async getByName(Name = this.name) {
2022-04-06 22:21:50 +03:00
try {
const user = await UserModel.findOne({ name: Name });
2022-04-06 21:57:12 +03:00
2022-04-06 22:21:50 +03:00
if (!user) return null;
2022-04-06 21:14:46 +03:00
2022-04-06 22:21:50 +03:00
const { id, name = "guest", avatar = "/images/guest.png", time = Date.now(), admin = false, deleted = false } = user;
this.id = Number(id);
this.name = name;
this.avatar = avatar;
this.time = time;
this.admin = admin;
this.deleted = deleted;
return this;
} catch (e) {
return null;
}
2022-04-06 21:57:12 +03:00
2022-03-13 17:12:09 +03:00
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
async takeId() {
this.id = await UserModel.count({}) || 0;
return this;
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
async write(id = this.id) {
const writing = await UserModel.findOneAndUpdate({ id }, this);
2022-03-13 16:16:46 +03:00
2022-04-06 21:14:46 +03:00
if (!writing)
await UserModel.create(this);
return this;
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
2022-03-13 16:16:46 +03:00
getLink(id = this.id) {
return "/users/" + id;
}
2022-02-26 21:26:27 +03:00
}