12-blog-获取所关注作者的文章列表

208 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情

前言:

场景:只看我关注的作者发布的文章。

正文

获取我本人登录账号

const fansEmail = req.user.email;

获取登录用户(我)关注的作者

const query = `SELECT userEmail FROM followers WHERE followorEmail = "${fansEmail}" `
const followAuthors = await sequelize.query(query) //是个email数组

我关注的作者信息被存放在这个followAuthors数组里。

我们先拿到他们的账号:

let followAuthorEmails =[]
for (const item of followAuthors[0]) {
    followAuthorEmails.push(item.userEmail) //只拿到email账号
}

image.png

在拿到他们的文章:

通过批量查询的方式,拿到关注作者们的所有文章,包括标签与作者,使用如下语句:

 let result = await Article.findAndCountAll({
            distinct:true, //去重
            where:{
                userEmail:followAuthorEmails //可以直接等于一个数组
            },
            include:[Tag,User]
})

打印一下result:

image.png

可以看到它里面有一个rows属性,里面含有dataValues,就是作者的所有文章集合了。

拿出rows打印可以看见,它是一个包含了所有作者文章信息的数组。

 let {rows} = await Article.findAndCountAll({
            distinct:true,
            where:{
                userEmail:followAuthorEmails //可以直接等于一个数组
            },
            include:[Tag,User]
        })

下一步

內部遍历rows数组

拿出每一条作者文章信息。

for(const t of rows) 的方式 拿出每一个作者文章t

打印一下每条数据,其中之一显示了文章标题,描述,内容,标签,作者等所有信息。

 dataValues: {
    slug: '13c56f25',
    title: 'lily-blog',
    description: 'Day10-08',
    body: '1.create 2.write',
    createdAt: 2022-10-08T10:00:32.000Z,
    updatedAt: 2022-10-08T10:00:32.000Z,
    UserEmail: 'lily@163.com', //要将它删掉
    Tags: [ [Tag] ],  //这是复杂的数据哦
    User: User { //这也是复杂的数据哦
      dataValues: [Object],
      _previousDataValues: [Object],
      uniqno: 1,
      _changed: Set(0) {},
      _options: [Object],
      isNewRecord: false
    }
  }

处理tag

进一步,只需要将每一个信息都遍历出来并将Tag标签重新拿出来name并放回数组。

const tags = []
for (const tag of t.dataValues.Tags) {
       tags.push(tag.name) // 拿出name重新放回去
}
t.dataValues.tags= tags; //再放回去

处理一下用户隐私信息:

//处理用户信息
let author = t.User
console.log(author,"author");

打印一下作者的数据,发现有很多隐私信息,要删除完再放回去哦

image.png

delete author.dataValues.password
delete t.dataValues.UserEmail
delete t.dataValues.Tags
t.dataValues.author = author //再放回去

每个t数据都处理完了,现在可以将处理过的t数据放在数组中作为返回数据了。

const article = []
articles.push(t.dataValues)

最后响应数据:

 return res.status(200)
              .json({
               message:"获取成功",
               data:articles
})