灏天阁

Node/Koa2[64]:自己关注自己

· Yin灏

首页要展示自己的微博,和自己所有关注的人的微博。

自己关注自己

创建用户时候,自己要关注自己

// src/services/user.js
const { addFollower } = require("./user-relation");
async function createUser({ userName, password, gender = 3, nickName }) {
  // 添加注册用户信息到数据库
  const result = await User.create({
    userName,
    password,
    nickName: nickName ? nickName : userName,
    gender,
  });

  const data = result.dataValues;
  // 自己关注自己,方便首页获取数据
  addFollower(data.id, data.id);
  return data;
}

处理获取粉丝函数,将自己排除掉

// src/services/user-relation.js
const { User, UserRelation } = require('../db/model/index');
const { formatUser } = require('./_format');

const Sequelize = require('sequelize');

// 获取该用户的粉丝
asyns function getUsersByFollower(followerId) {
  const result = await User.findAndCountAll({
    attributes: ['id', 'userName', 'nickName', 'picture'],
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: UserRelation,
        where: {
          followerId,
          // 排除自己的 userId
          userId: {
            [Sequelize.Op.ne]: followerId
          }
        }
      }
    ]
  });
  let userList = result.rows.map(row => row.dayaValues);
  userList = formatUser(userList);
  return {
    count: result.count,
    userList
  }
}
// 获取关注人列表
async function getFollowersByUser(userId) {
  const result = await UserRelation.findAndCountAll({
    order: [["id", "desc"]],
    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "picture"],
      },
    ],
    where: {
      userId,
      followerId: {
        [Sequelize.Op.ne]: 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,
  };
}

- Book Lists -