Node/Koa2[51]: 个人主页
·
Yin灏
-
模板和路由(后端渲染数据 SSP)
-
记载更多
-
单元测试
页面和模板
src/views/profile.ejs
页面路由
src/routes/view/blog.js
//...
const { getProfileBlogList } = require("../../controller/blog-profile");
// 个人主页
//...
router.get("/profile", loginRedirect, async (ctx, next) => {
const { userName } = ctx.session.userInfo;
ctx.redirect(`/profile/${userName}`);
});
router.get("/profile/:userName", loginRedirect, async (ctx, next) => {
const { userName: curUserName } = ctx.params;
// controller 层
const result = await getProfileBlogList(curUserName, 0);
const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;
await ctx.render("profile", {
blogData: {
isEmpty,
blogList,
pageSize,
pageIndex,
count,
},
});
});
//...
定义 pageSize 常量
src/conf/constant.js
module.exports = {
//...
PAGE_SIZE: 5,
};
controller 层
src/controller/blog-profile.js
//...
const { getBlogListByUser } = require("../services/blog");
const { PAGE_SIZE } = require("../conf/constant");
const { SuccessModel } = require("../model/ResModel");
// 个人主页
async function getProfileBlogList(userName, pageIndex = 0) {
// services 层
const result = await getBlogListByUser({
userName,
pageIndex,
pageSize: PAGE_SIZE,
});
const blogList = result.blogList;
return new SuccessModel({
isEmpty: blogList.length === 0,
blogList,
pageSize: PAGE_SIZE,
pageIndex
count: result.count
});
}
module.exports = {
getProfileBlogList,
};
services 层
src/services/blog.js
//...
const { Blog, User } = require("../db/model/index");
const { formatUser } = require("./_format");
//...
async function getBlogListByUser({ userName, pageIndex = 0, pageSize = 10 }) {
// 查询数据库
const userWhereOpts = {};
if (userName) {
userWhereOpts.userName = userName;
}
const result = await Blog.findAndCountAll({
limit: pageSize,
offset: pageSize * pageIndex,
order: [["id", "desc"]],
include: [
{
model: User,
attributes: ["userName", "nickName", "picture"],
where: userWhereOpts,
},
],
});
// result.count 总数,与分页无关
// result.rows 查询结果,数组
let blogList = result.rows.map((row) => row.dataValues);
blogList = blogList.map((blogItem) => {
const user = blogItem.user.dataValues;
blogItem.user = formatUser(user);
return blogItem;
});
return {
count: result.count,
blogList,
};
}
module.exports = {
//...
getBlogListByUser,
};