akf-forum/routes/api/routes/messages.js

73 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-08-11 17:55:48 +03:00
const { MessageModel, ThreadModel } = require("../../../models");
2022-08-10 02:08:18 +03:00
const rateLimit = require('express-rate-limit')
2022-04-03 22:03:47 +03:00
const { Router } = require("express")
const app = Router();
2022-08-11 17:55:48 +03:00
2022-04-06 21:14:46 +03:00
app.get("/:id", async (req, res) => {
2022-04-03 22:03:47 +03:00
2022-08-10 02:08:18 +03:00
const message = await MessageModel.get(id);
2022-04-03 22:03:47 +03:00
2022-08-11 18:15:27 +03:00
if (!message || (message.deleted && req.user && !req.user.admin)) return res.error(404, `We don't have any thread with id ${id}.`);
2022-04-03 22:03:47 +03:00
res.complate(message.toObject({ virtuals: true }));
2022-04-03 22:03:47 +03:00
})
2022-08-10 02:08:18 +03:00
app.post("/", rateLimit({
windowMs: 60_000, max: 1, standardHeaders: true, legacyHeaders: false,
handler: (request, response, next, options) =>
!request.user.admin ?
response.error(options.statusCode, "You are begin ratelimited")
: next()
}), async (req, res) => {
2022-04-03 22:03:47 +03:00
const { threadID = null, content = null } = req.body;
2022-08-10 02:08:18 +03:00
if (!content) return res.error(400, "Missing message content in request body.");
2022-04-03 22:03:47 +03:00
2022-08-10 02:08:18 +03:00
const thread = await ThreadModel.get(threadID);
2022-04-03 22:03:47 +03:00
if (!thread) return res.error(404, `We don't have any thread with id ${threadID}.`);
2022-04-03 22:03:47 +03:00
2022-08-10 02:08:18 +03:00
const message = await new MessageModel({ content, author: req.user, threadID: thread.id }).takeId();
await message.save();
await thread.push(message.id).save();
2022-04-03 22:03:47 +03:00
res.complate(message.toObject({ virtuals: true }));
2022-04-03 22:03:47 +03:00
})
2022-08-11 00:38:44 +03:00
app.post("/:id/react/:type", async (req, res) => {
const message = await MessageModel.get(req.params.id);
if (message) {
if (req.user.id in message.react)
delete message.react[req.session.userid];
else
message.react[req.session.userid] = req.params.type === "like";
message.markModified("react");
await message.save();
res.complate(message.toObject({ virtuals: true }));
2022-08-11 18:15:27 +03:00
} else error(res, 404, `We don't have any message with id ${req.params.id}.`);
2022-08-11 00:38:44 +03:00
});
2022-04-03 22:03:47 +03:00
app.post("/:id/delete", async (req, res) => {
const message = await MessageModel.get(req.params.id);
if (!message || (message.deleted && req.user && !req.user.admin)) return res.error(404, "We have not got any message declared as this id.");
const user = req.user;
if (user.id != message.authorID && !user.admin)
return res.error(403, "You have not got permission for this.");
message.deleted = true;
await message.save();
res.complate(message.toObject({ virtuals: true }));
})
2022-04-03 22:03:47 +03:00
module.exports = app;