添加喜欢

  • 获取参数(文章)
  • 获取文章 : 包含tag
  • 添加喜欢 : 文章 添加被喜欢的用户
  • 获取文章作者
  • 获取喜欢个数
  • 数据处理:标签 / 作者 / 喜欢个数
  • 响应数据

封装方法

  1. function handleArticle(article,author,count){
  2. const newTags = []
  3. for (const t of article.dataValues.tags) {
  4. newTags.push(t.name)
  5. }
  6. article.dataValues.tags = newTags
  7. // console.log(author);
  8. delete author.dataValues.password
  9. delete author.dataValues.email
  10. article.dataValues.author = author
  11. article.dataValues.favoriteCount = count
  12. article.dataValues.favorited = true
  13. return article.dataValues
  14. }

编码实现

  1. // 添加喜欢
  2. module.exports.addFavorite = async (req, res,next) => {
  3. try {
  4. // ● 获取参数(文章)
  5. const {slug} = req.params
  6. // ● 获取文章 : 包含tag
  7. let article = await Article.findByPk(slug,{include:Tag})
  8. if(!article){
  9. throw new HttpException(404,'喜欢文章不存在','article not found')
  10. }
  11. // ● 添加喜欢 : 文章 添加被喜欢的用户
  12. // console.log(article.__proto__); //addUsers
  13. await article.addUsers(req.user.email) // 文章添加喜欢用户 : 文章可以被多个人喜欢
  14. // ● 获取文章作者
  15. const author = await article.getUser()
  16. // ● 获取喜欢个数
  17. const count = await article.countUsers()
  18. // ● 数据处理:标签 / 作者 / 喜欢个数
  19. article = handleArticle(article,author,count)
  20. // ● 响应数据
  21. res.status(200).json({
  22. status:1,
  23. messagae:'喜欢文章成功',
  24. data:article
  25. })
  26. } catch (error) {
  27. next(error)
  28. }
  29. };

取消喜欢

  1. module.exports.removeFavorite = async (req, res,next) => {
  2. try {
  3. // ● 获取参数(文章)
  4. const {slug} = req.params
  5. // ● 获取文章 : 包含tag
  6. let article = await Article.findByPk(slug,{include:Tag})
  7. if(!article){
  8. throw new HttpException(404,'喜欢文章不存在','article not found')
  9. }
  10. // ● 取消喜欢
  11. // console.log(article.__proto__); //addUsers
  12. await article.removeUsers(req.user.email)
  13. // ● 获取文章作者
  14. const author = await article.getUser()
  15. // ● 获取喜欢个数
  16. const count = await article.countUsers()
  17. // ● 数据处理:标签 / 作者 / 喜欢个数
  18. article = handleArticle(article,author,count)
  19. // ● 响应数据
  20. res.status(200).json({
  21. status:1,
  22. messagae:'取消喜欢文章成功',
  23. data:article
  24. })
  25. } catch (error) {
  26. next(error)
  27. }
  28. };