akf-forum/classes/user.js

64 lines
1.6 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-03-13 16:16:46 +03:00
this.id = Number(id);
2022-04-06 21:14:46 +03:00
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;
2022-03-13 16:16:46 +03:00
this.name = name;
this.avatar = avatar;
2022-03-13 17:12:09 +03:00
this.time = time;
2022-03-13 16:16:46 +03:00
this.admin = admin;
2022-03-13 17:12:09 +03:00
this.deleted = deleted;
2022-04-06 21:14:46 +03:00
return this;
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) {
const user = await UserModel.findOne({ name: Name });
2022-03-13 17:12:09 +03:00
if (!user) return null;
2022-04-06 21:14:46 +03:00
const { name = "guest", avatar = "/images/guest.png", time = Date.now(), admin = false, deleted = false } = user;
2022-03-13 17:12:09 +03:00
this.name = name;
this.avatar = avatar;
this.time = time;
this.admin = admin;
this.deleted = deleted;
2022-04-03 21:01:55 +03:00
return this;
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
}