akf-forum/routes/threads.js

69 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-03-21 23:53:22 +03:00
const { Router } = require("express");
const app = Router();
2022-04-06 21:14:46 +03:00
const { Thread, Message, User } = require("../classes");
const error = require("../errors/error")
const { ThreadModel } = require("../models")
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
app.get("/", async (req, res) => {
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
const user = req.user;
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
const threads = await Promise.all((await ThreadModel.find({}).limit(10))
.map(async threads => await new Thread().getById(threads.id)));
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
return res.render("threads", { threads, user });
2022-03-21 23:53:22 +03:00
});
2022-04-06 21:14:46 +03:00
app.get("/open*", async (req, res) => {
2022-04-03 21:39:26 +03:00
2022-04-06 21:14:46 +03:00
const user = req.user
2022-04-03 21:39:26 +03:00
res.render("openThread", { user })
});
2022-04-06 21:14:46 +03:00
app.get("/:id", async (req, res) => {
2022-03-21 23:53:22 +03:00
const { id } = req.params;
2022-04-06 21:14:46 +03:00
const thread = await new Thread().getById(id);
2022-03-21 23:53:22 +03:00
if (thread) {
2022-04-06 21:14:46 +03:00
const user = req.user;
const messages = await Promise.all(thread.messages.map(async id => {
const message = await new Message().getById(id)
return (message.deleted || !message) ? null : message;
}));
2022-03-21 23:53:22 +03:00
res.render("thread", { thread, messages, user })
} else
error(res, 404, "We have not got this thread.");
});
2022-04-03 21:01:55 +03:00
2022-04-03 21:39:26 +03:00
app.use(require("../middlewares/login"));
2022-04-03 21:01:55 +03:00
2022-04-06 21:14:46 +03:00
app.post("/", async (req, res) => {
2022-03-21 23:53:22 +03:00
const { title = null, content = null } = req.body;
2022-04-06 21:14:46 +03:00
if (!title || !content) return error(res, 400, "Title and/or content is missing");
const user = req.user
const thread = await new Thread(title, user).takeId()
const message = await new Message(content, user, thread.id).takeId()
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
thread.push(message.id).write();
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
message.write();
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
res.redirect('/threads/' + thread.id);
2022-03-21 23:53:22 +03:00
})
module.exports = app;