akf-forum/routes/threads.js

68 lines
1.5 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 error = require("../errors/error")
const { ThreadModel, MessageModel } = 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
const threads = await ThreadModel.find({}).limit(10);
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
});
app.get("/create*", async (req, res) => {
2022-04-03 21:39:26 +03:00
2022-04-06 21:14:46 +03:00
const user = req.user
res.render("createThread", { user })
2022-04-03 21:39:26 +03:00
});
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;
const thread = await ThreadModel.get(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 MessageModel.get(id)
2022-04-06 21:14:46 +03:00
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 ThreadModel({ title, author: user }).takeId()
const message = await new MessageModel({ content, author: user, threadID: thread.id }).takeId()
2022-03-21 23:53:22 +03:00
await thread.push(message.id).save();
2022-03-21 23:53:22 +03:00
await message.save();
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;