2022-03-21 23:53:22 +03:00
|
|
|
const { Router } = require("express");
|
|
|
|
const app = Router();
|
2022-09-09 20:47:28 +03:00
|
|
|
const { ThreadModel, MessageModel, CategoryModel } = require("../models")
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-04-06 21:14:46 +03:00
|
|
|
app.get("/", async (req, res) => {
|
2022-09-01 15:19:12 +03:00
|
|
|
const page = Number(req.query.page) || 0;
|
2022-09-21 23:54:48 +03:00
|
|
|
const query = req.user?.admin ? {} : { state: "OPEN" };
|
2022-09-17 21:36:33 +03:00
|
|
|
let threads = await ThreadModel.find(query).limit(10).skip(page * 10).sort({ time: -1 });
|
2022-08-31 14:44:28 +03:00
|
|
|
threads = await Promise.all(threads.map(thread => thread.get_author()));
|
2022-09-01 15:19:12 +03:00
|
|
|
|
2022-09-16 23:51:16 +03:00
|
|
|
return res.reply("threads", { threads, page, title: "Threads", desp: threads.length + " threads are listed", pages: Math.ceil(await ThreadModel.count(query) / 10) });
|
2022-03-21 23:53:22 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
|
2022-09-09 20:47:28 +03:00
|
|
|
app.get("/create/", async (req, res) => res.reply("create_thread", { categories: await CategoryModel.find() }));
|
2022-04-03 21:39:26 +03:00
|
|
|
|
2022-08-29 16:16:44 +03:00
|
|
|
app.get("/:id/", async (req, res) => {
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-08-29 16:16:44 +03:00
|
|
|
const { user, params: { id } } = req
|
2022-04-06 21:14:46 +03:00
|
|
|
|
2022-08-31 14:44:28 +03:00
|
|
|
const page = Number(req.query.page || 0);
|
2022-08-29 19:31:59 +03:00
|
|
|
|
2022-08-29 16:16:44 +03:00
|
|
|
const thread = await ThreadModel.get(id)
|
2022-09-21 23:54:48 +03:00
|
|
|
if (thread && (user?.admin || thread.state == "OPEN")) {
|
2022-09-09 16:30:57 +03:00
|
|
|
thread.count = await thread.messageCount(user?.admin);
|
|
|
|
thread.pages = Math.ceil(thread.count / 10);
|
2022-08-29 16:16:44 +03:00
|
|
|
thread.views++;
|
2022-08-29 19:31:59 +03:00
|
|
|
const query = { threadID: id };
|
2022-08-29 16:16:44 +03:00
|
|
|
if (!user || !user.admin) query.deleted = false;
|
|
|
|
|
2022-08-31 14:44:28 +03:00
|
|
|
const messages = await Promise.all(await MessageModel.find(query).sort({ time: 1 }).limit(10).skip(page * 10)
|
2022-09-16 21:57:27 +03:00
|
|
|
.then(messages => messages.map(message => message.get_author())));
|
|
|
|
|
2022-09-16 23:38:06 +03:00
|
|
|
res.reply("thread", { page, thread, messages });
|
2022-08-29 16:16:44 +03:00
|
|
|
|
|
|
|
thread.save();
|
2022-08-28 18:19:03 +03:00
|
|
|
|
|
|
|
} else
|
2022-08-29 19:31:59 +03:00
|
|
|
res.error(404, `We don't have any thread with id ${id}.`);
|
2022-03-21 23:53:22 +03:00
|
|
|
});
|
|
|
|
|
2022-04-03 21:01:55 +03:00
|
|
|
|
2022-03-21 23:53:22 +03:00
|
|
|
module.exports = app;
|