如何使用 axios 分页从 firebase 获取批量数据?

How to paginate getting bulk data from firebase with axios?

假设我有 1000 多篇博文。使用 axios 从 firebase 获取数据并存储在 nuxtServerInit 中的最佳实践是什么?

我能否以某种方式在第一次加载时先获取前 10 篇博文,然后再获取更多数据?

现在我有如下 vuex 操作:

nuxtServerInit(vuexContext, context) {
    return axios
      .get('https://my-blog.firebaseio.com/posts.json')
      .then(res => {
        const postsArray = []
        for (const key in res.data) {
          postsArray.push({ ...res.data[key], uid: key })
        }
        vuexContext.commit('setPosts', postsArray)
      })
      .catch(e => context.error(e))
  },

您正在使用 REST API to access the Firebase Database. To retrieve a limited number of items, use a limit query

https://my-blog.firebaseio.com/posts.json?limitToFirst=10

由于限制只有在您知道项目的排序方式时才有意义,因此您还需要 order the items,即在它们的键上:

https://my-blog.firebaseio.com/posts.json?orderBy="$key"&limitToFirst=10

请注意,结果可能未排序,因为 JSON 对象中的属性顺序未定义。所以结果包含前10个post,但可能不会以正确的顺序显示它们。

下一步是获取接下来的 10 个项目。与大多数传统数据库不同,Firebase 在其查询中不支持偏移子句。所以你不能告诉它跳过前 10 项以进入下 10 项。

而不是 Firebase queries use anchors/ranges:您必须知道上一页的最后一项才能为下一页构建查询。假设第 10 个 post 有一个 keyOfPost10 的键,那么你可以得到下一页:

https://my-blog.firebaseio.com/posts.json?orderBy="$key"&startAt="keyOfPost10"&limitToFirst=11

我们需要在此处检索 11 个 post,因为我们还要获取第 10 个 post。这也意味着您需要过滤客户端代码中重叠的 post。