1const { Board, Post, User, Reply } = require("../models");
2const { displayDateTime } = require("../helpers");
3
4const getNewReplyPage = async (req, res, next) => {
5 try {
6 const post = await Post.findOne({
7 where: {
8 slug: req.params.post_slug,
9 },
10 attributes: [
11 "id",
12 "name",
13 "content",
14 "renderedContent",
15 "createdAt",
16 "slug",
17 ],
18 include: [
19 {
20 model: Board,
21 as: "board",
22 attributes: ["id", "name", "slug"],
23 },
24 {
25 model: User,
26 as: "author",
27 attributes: ["id", "username", "avatar"],
28 },
29 ],
30 });
31
32 if (!post) {
33 const err = {
34 message: "Post to reply for, is not found!",
35 status: 404,
36 };
37 next(err);
38 return;
39 }
40
41 post.createdAtFormatted = displayDateTime(post.createdAt);
42
43 const breadcrumbData = [
44 { link: "/", name: "Index" },
45 { link: `/b/${post.board.slug}`, name: post.board.name },
46 { link: `/p/${post.slug}`, name: post.name },
47 { name: "New Reply" },
48 ];
49
50 res.render("new_reply", { title: "New Reply", post, breadcrumbData });
51 return;
52 } catch (e) {
53 console.log(e);
54 next(e);
55 return;
56 }
57};
58
59const createNewReply = async (req, res, next) => {
60 try {
61 const post = await Post.findOne({
62 where: {
63 id: req.xop.postId,
64 },
65 attributes: ["id", "slug"],
66 });
67
68 if (!post) {
69 const err = {
70 message: "Post to reply for, is not found!",
71 status: 404,
72 };
73 next(err);
74 return;
75 }
76
77 const url = `/p/${post.slug}`;
78
79 const newReply = await Reply.create({
80 postId: req.xop.postId,
81 content: req.xop.content,
82 createdByUser: req.session.user.id,
83 });
84
85 //TODO: check if creating reply failed
86
87 res.redirect(url);
88 return;
89 } catch (e) {
90 console.log(e);
91 next(e);
92 return;
93 }
94};
95
96module.exports = {
97 getNewReplyPage,
98 createNewReply,
99};