akf-forum/classes/thread.js

59 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-03-13 16:16:46 +03:00
const User = require("./user")
2022-04-06 21:14:46 +03:00
const { ThreadModel } = require("../models");
2022-03-13 16:16:46 +03:00
module.exports = class Thread {
2022-04-06 21:14:46 +03:00
constructor(title, author = User, messages = [], time = Date.now(), deleted = false) {
2022-03-13 16:16:46 +03:00
this.author = author;
2022-04-06 21:14:46 +03:00
this.authorID = author?.id;
2022-03-13 16:16:46 +03:00
this.title = title;
this.messages = messages;
this.time = time;
this.deleted = deleted;
}
2022-04-06 21:14:46 +03:00
async getById(id = this.id) {
this.id = Number(id);
2022-04-06 21:14:46 +03:00
const thread = await ThreadModel.findOne({ id });
if (!thread) return null;
const { title, authorID, author, messages = [], time = Date.now(), deleted = false } = thread;
2022-03-13 16:16:46 +03:00
this.title = title
2022-04-06 21:14:46 +03:00
this.author = author;
this.authorID = authorID;
2022-03-13 16:16:46 +03:00
this.messages = messages;
this.time = time;
this.deleted = deleted;
2022-03-13 17:12:09 +03:00
return this;
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
push(messageID) {
this.messages.push(messageID)
return this;
2022-03-13 16:16:46 +03:00
}
2022-04-06 21:14:46 +03:00
async takeId() {
this.id = await ThreadModel.count({}) || 0;
2022-03-13 16:16:46 +03:00
return this;
}
2022-04-06 21:14:46 +03:00
async write(id = this.id) {
const writing = await ThreadModel.findOneAndUpdate({ id }, this);
if (!writing)
await ThreadModel.create(this);
2022-03-13 16:16:46 +03:00
return this;
}
2022-04-06 21:14:46 +03:00
getLink(id = this.id) {
return "/threads/" + id;
2022-03-13 16:16:46 +03:00
}
2022-02-26 21:26:27 +03:00
}