灏天阁

Node/Koa2[57]: 开发粉丝列表

· Yin灏

src/routes/view/blog.js

//...
const { getProfileBlogList } = require("../../controller/blog-profile");
const { getFans } = 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;

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

controller

src/controller/user-relation.js

const { getUsersByFollower } = require("../services/user-relation");
async function getFans(userId) {
  // services
  const { count, userList } = await getUsersByFollower(userId);
  return new SuccessModel({
    count,
    userList,
  });
}
module.exports = {
  getFans,
};

services

src/services/user-relation.js

const { User, UserRelation } = require('../db/model/index');
const { formatUser } = require('./_format');
// 获取该用户的粉丝
asyns function getUsersByFollower(followerId) {
  const result = await User.findAndCountAll({
    attributes: ['id', 'userName', 'nickName', 'picture'],
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: UserRelation,
        where: {
          followerId
        }
      }
    ]
  });
  let userList = result.rows.map(row => row.dayaValues);
  userList = formatUser(userList);
  return {
    count: result.count,
    userList
  }
}

module.exports = {
  getUsersByFollower
}

- Book Lists -