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) {
|
2022-04-06 22:21:50 +03:00
|
|
|
try {
|
|
|
|
this.id = Number(id);
|
2022-04-06 21:14:46 +03:00
|
|
|
|
|
|
|
|
2022-04-06 22:21:50 +03:00
|
|
|
const thread = await ThreadModel.findOne({ id });
|
|
|
|
if (!thread) return null;
|
2022-03-13 16:16:46 +03:00
|
|
|
|
2022-04-06 22:21:50 +03:00
|
|
|
const { title, authorID, author, messages = [], time = Date.now(), deleted = false } = thread;
|
|
|
|
this.title = title
|
|
|
|
this.author = author;
|
|
|
|
this.authorID = authorID;
|
|
|
|
this.messages = messages;
|
|
|
|
this.time = time;
|
|
|
|
this.deleted = deleted;
|
|
|
|
|
|
|
|
return this;
|
|
|
|
} catch (e) {
|
|
|
|
return null;
|
|
|
|
}
|
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 22:21:50 +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
|
|
|
}
|