使用koa+mongodb构建的仿知乎接口(三)

498 阅读1分钟

好了,今天要实现的需求是什么呢?一个社区一般必定会有关注他人、取消关注或者被他人关注的需求。所以,我们就以知乎上的关注、取消关注、正在关注列表、粉丝列表为原型进行开发。

关注和取消关注

  1. 继续增加UserSchema中的字段
const UserSchema = new Schema({
  ...,
  following: {
    type: [{type: Schema.Types.ObjectId, ref: 'User'}],
    select: false
  }
})
  1. 编写转发的路由
// 关注谁
router.put('/follow/:id', auth, follow)
// 取消关注谁
router.delete('/unfollow/:id', auth, unfollow)
  1. 使用数据模型编写控制器逻辑
async follow (ctx) {
  const me = await User.findById(ctx.state.user._id).select('+following');
  if (!me.following.map(id => id.toString()).includes(ctx.params.id)) {
    me.following.push(ctx.params.id);
    me.save();
  }
  ctx.status = 204;
}
async unfollow (ctx) {
  let user = await User.findById(ctx.state.user._id).select('+following')
  let index = user.following.map(id=>id.toString()).indexOf(ctx.params.id)
  if(index > -1) {
    user.following.splice(index)
    user.save()
  }
  ctx.status = 204
}
  1. 使用Postman测试

获取粉丝列表和正在关注列表

  1. 编写转发的路由
// 谁的粉丝
router.get('/:id/listenFollower', listenFollower)
// 谁关注了什么人
router.get('/:id/listenFollowing', listenFollowing)
  1. 使用数据模型编写控制器逻辑
async listenFollowing (ctx) {
  let user = await User.findById(ctx.params.id).select('+following').populate('following')
  if (!user) {ctx.throw(404)}
  ctx.body = user.following
}
async listenFollower(ctx) {
  const users = await User.find({following: ctx.params.id})
  ctx.body = users
}
  1. 使用Postman测试

总结:

1.用户关注和取消关注,是需要鉴权的过程的。