灏天阁

Node/Koa2[65]:首页模板和路由处理

· Yin灏

首页模板

# src/views/index.ejs

首页路由处理

// src/routes/view/blog.js
const { getHomeBlogList } = require("../../controller/blog-home");
router.get("/", loginRedirect, async (ctx, next) => {
  const userInfo = ctx.session.userInfo;
  const { id: userId } = userInfo;
  // 获取第一页数据
  // 调用 controller
  const result = await getHomeBlogList(userId);
  const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;
  // 获取粉丝
  const fansResult = await getFans(userId);
  const { count: fansCount, fansList } = fansResult.data;
  // 获取关注人列表
  const followersResult = await getFollowers(userId);
  const { count: followersCount, followersList } = followersResult.data;
  await ctx.render("index", {
    userData: {
      userInfo,
      fansData: {
        count: fansCount,
        list: fansList,
      },
      followersData: {
        count: followersCount,
        list: followersList,
      },
    },
    blogData: {
      isEmpty,
      blogList,
      pageSize,
      pageIndex,
      count,
    },
  });
});

处理 controller

// src/controller/blog-home.js
const { getFollowersBlogList } = require("../services/blog");
async function getHomeBlogList(userId, pageIndex = 0) {
  // 调用 services
  const { count, blogList } = await getFollowersBlogList({
    userId,
    pageIndex,
    PAGE_SIZE,
  });
  return new SuccessModel({
    isEmpty: blogList.length === 0,
    blogList,
    pageSize: PAGE_SIZE,
    pageIndex,
    count,
  });
}

处理 services

// src/services/blog.js
async function getFollowersBlogList({ userId, pageIndex = 0, pageSize = 10 }) {
  // 三表查询
  const result = await Blog.findAndCountAll({
    limit: pageSize,
    offset: pageSize * pageIndex,
    order: [["id", "desc"]],
    include: [
      {
        model: User,
        attributes: ["userName", "nickName", "picture"],
      },
      {
        model: UserRelation,
        // followerId 被关注者,也就是我关注的人
        attributes: ["userId", "followerId"],
        where: {
          userId,
        },
      },
    ],
  });
  // 返回数据结构
  /*
  {
      rows: [
        {
          id: 1,
          title: "Example Blog",
          content: "Lorem ipsum dolor sit amet...",
          User: {
            userName: "exampleUser",
            nickName: "John Doe",
            picture: "https://example.com/profile.jpg",
          },
          UserRelation: {
            userId: 2,
            followerId: 1,
          }
        },
        // More rows...
      ],
      count: 10
    }
  */
  let blogList = result.rows.map((row) => row.dataValues);
  blogList = formatBlog(blogList);
  blogList = blogList.map((blogItem) => {
    blogItem.user = formatUser(blogItem.user.dataValues);
    return blogItem;
  });
  return {
    count: result.count,
    blogList,
  };
}

- Book Lists -