灏天阁

Node/Koa2[61]:关注人列表

· Yin灏

关注人列表模板

src/views/widgets/followers.ejs

获取相关数据

src/routes/view/blog.js

//...
const { getProfileBlogList } = require("../../controller/blog-profile");
const { getFans, getFollowers } = require("../../controller/user-relation");
// 个人主页
//...
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 myUserInfo = ctx.session.userInfo;
  const myUserName = myUserInfo.userName;

  let curUserInfo;
  const { userName: curUserName } = ctx.params;
  const isMe = myUserName === curUserName;
  if (isMe) {
    curUserInfo = myUserInfo;
  } else {
    const existResult = await isExist(curUserName);
    if (existResult.error !== 0) {
      return; // 用户名不存在
    }
    // 用户名存在
    curUserInfo = existResult.data;
  }
  // controller 层
  const result = await getProfileBlogList(curUserName, 0);
  const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;

  // 获取粉丝
  // controller 层
  const fansResult = await getFans(curUserInfo.id);
  const { count: fansCount, userList: fansList } = fansResult.data;

  // 获取关注人列表
  // 调用 controller
  const followersResult = await getFollowers(curUserInfo.id);
  const { count: followersCount, followersList } = followersResult.data;

  // 我是否关注了此人?
  const amIFollowed = fansList.some((item) => {
    return item.userName === myUserName;
  });

  await ctx.render("profile", {
    blogData: {
      isEmpty,
      blogList,
      pageSize,
      pageIndex,
      count,
    },
    userData: {
      userInfo: curUserInfo,
      isMe,
      amIFollowed,
      fansData: {
        count: fansCount,
        list: fansList,
      },
      followersData: {
        count: followersCount,
        list: followersList,
      },
    },
  });
});
//...

controller 层

src/controller/user-relation.js

//...
const { getFollowersByUser } = require("../services/user-relation");
async function getFollowers(userId) {
  // 调用 services
  const { count, userList } = await getFollowersByUser(userId);
  return new SuccessModel({
    count,
    followersList: userList,
  });
}
module.exports = {
  //...
  getFollowers,
};
//...

services 层

src/services/user-relation.js

//...
async function getFollowersByUser(userId) {
  const result = await UserRelation.findAndCountAll({
    order: [["id", "desc"]],
    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "picture"],
      },
    ],
    where: {
      userId,
    },
  });
  let userList = result.rows.map((row) => row.dataValues);
  userList = userList.map((item) => {
    let user = item.user;
    user = user.dataValues;
    user = formatUser(user);
    return user;
  });
  return {
    count: result.count,
    userList,
  };
}
module.exports = {
  //...
  getFollowersByUser,
};
//...

- Book Lists -