litebb/controllers/general.controller.js

1const Sequelize = require("sequelize"); 2 3const { Board, Post, User, Reply } = require("../models"); 4const { displayDate } = require("../helpers"); 5 6const getIndexPage = async (req, res, next) => { 7 try { 8 const boards = await Board.findAll({ 9 attributes: ["id", "name", "slug", "description"], 10 }); 11 12 // get latest 15 posts and links to them 13 const posts = await Post.findAll({ 14 attributes: ["id", "slug", "name", "createdAt"], 15 order: [["createdAt", "DESC"]], 16 limit: 15, 17 include: [ 18 { 19 model: User, 20 as: "author", 21 attributes: ["id", "username"], 22 }, 23 { 24 model: Board, 25 as: "board", 26 attributes: ["id", "name"], 27 }, 28 ], 29 }); 30 31 const results = JSON.parse(JSON.stringify(posts)); 32 const datedPosts = results.map((p) => ({ 33 ...p, 34 created_date_formatted: displayDate(p.createdAt), 35 })); 36 37 // console.log(datedPosts) 38 res.render("index", { title: "Home", boards, posts: datedPosts }); 39 return; 40 } catch (e) { 41 console.log(e); 42 next(e); 43 return; 44 } 45}; 46 47const getBoardIndexPage = async (req, res, next) => { 48 try { 49 const board = await Board.findOne({ 50 where: { 51 slug: req.params.board_slug, 52 }, 53 attributes: ["id", "name"], 54 }); 55 56 // get paginated posts in board too 57 // wesbos :) 58 const page = req.query.page || 1; 59 const limit = 25; 60 const skip = page * limit - limit; 61 62 // https://stackoverflow.com/questions/37817808/counting-associated-entries-with-sequelize 63 const postsQuery = Post.findAll({ 64 subQuery: false, 65 where: { 66 boardId: board.id, 67 }, 68 attributes: [ 69 "id", 70 "slug", 71 "name", 72 "createdAt", 73 [Sequelize.fn("COUNT", Sequelize.col("Replies.postId")), "replyCount"], 74 ], 75 order: [["createdAt", "DESC"]], 76 offset: skip, 77 limit: limit, 78 include: [ 79 { 80 model: User, 81 as: "author", 82 attributes: ["id", "username"], 83 }, 84 { 85 model: Board, 86 as: "board", 87 attributes: ["id", "name"], 88 }, 89 { 90 model: Reply, 91 attributes: [], 92 }, 93 ], 94 group: ["Post.id"], 95 }); 96 97 const countQuery = Post.count({ 98 where: { 99 boardId: board.id, 100 }, 101 }); 102 103 const [posts, count] = await Promise.all([postsQuery, countQuery]); 104 105 // console.log(JSON.stringify(posts)) 106 const pages = Math.ceil(count / limit); 107 108 const results = JSON.parse(JSON.stringify(posts)); 109 const datedPosts = results.map((p) => ({ 110 ...p, 111 created_date_formatted: displayDate(p.createdAt), 112 })); 113 114 const breadcrumbData = [{ link: "/", name: "Index" }, { name: board.name }]; 115 116 res.render("board", { 117 title: board.name, 118 posts: datedPosts, 119 page, 120 pages, 121 count, 122 breadcrumbData, 123 }); 124 return; 125 } catch (e) { 126 console.log(e); 127 next(e); 128 return; 129 } 130}; 131 132module.exports = { 133 getIndexPage, 134 getBoardIndexPage, 135}; 136