GraphQL 查询中 totalCount 一直为 0 的解决方案

在使用 GraphQL 进行数据查询时,我们经常会遇到 totalCount 始终为 0 的情况。这种情况通常发生在分页查询中,我们需要获取总记录数以便进行分页。本文将介绍这种情况的原因,以及如何解决。

问题原因

在 GraphQL 查询中,totalCount 通常是通过分页查询中的 pageInfo 对象来获取的。例如:

----- -
  ------------ --- -
    ----- -
      --
      ----
    -
    -------- -
      -----------
      ---------------
      -----------
      ---------
      ----------
    -
  -
-

然而,如果 totalCount 始终为 0,那么可能是因为我们没有正确配置 resolvers。

在 GraphQL 中,每个字段都可以有一个 resolver 函数,用于指定如何获取该字段的值。例如:

---- ----- -
  ------------ ----- --------
-

---- ---- -
  --- ---
  ----- -------
-

------ -
  ------ -----
-

在上面的代码中,我们定义了一个 users 查询,它接受一个 first 参数,用于指定查询的前几条记录。我们还定义了一个 User 类型,它包含 id 和 name 两个字段。

如果我们没有为 totalCount 字段指定 resolver 函数,那么它将始终返回默认值 0。因此,我们需要为它指定一个 resolver 函数,用于计算总记录数。

解决方案

为 totalCount 字段指定 resolver 函数的方法与为其他字段指定 resolver 函数的方法相同。我们只需要在 schema 中为它指定一个 resolver 函数即可。

例如,我们可以为上面的 schema 添加一个 totalCount 字段,并为它指定一个 resolver 函数:

---- ----- -
  ------------ ----- --------
-

---- ---- -
  --- ---
  ----- -------
-

---- -------- -
  ------------ --------
  ---------------- --------
  ------------ ------
  ---------- ------
  ----------- ----
-

------ -
  ------ -----
-

---- ----- -
  ------------ ----- --------
  ----------- ----
-

------ -
  ------ -----
-

----- --------- - -
  ------ -
    ------ -------- ----- -------- ----- -- -
      -- -------
    --
    ----------- -------- ----- -------- ----- -- -
      -- ------
    -
  -
--

在上面的代码中,我们为 schema 添加了一个 PageInfo 类型,它包含了 totalCount 字段。我们还为 schema 添加了一个 totalCount 查询,用于计算总记录数。最后,我们为 Query 对象添加了一个 totalCount resolver 函数,用于计算总记录数。

示例代码

以下是一个完整的示例代码,用于演示如何为 totalCount 字段指定 resolver 函数:

----- - ------------- --- - - -------------------------

----- -------- - ----
  ---- ----- -
    ------------ ----- --------
    ----------- ----
  -

  ---- ---- -
    --- ---
    ----- -------
  -

  ---- -------- -
    ------------ --------
    ---------------- --------
    ------------ ------
    ---------- ------
    ----------- ----
  -

  ------ -
    ------ -----
  -
--

----- --------- - -
  ------ -
    ------ -------- ----- -------- ----- -- -
      -- -------
    --
    ----------- -------- ----- -------- ----- -- -
      -- ------
    -
  -
--

----- ------ - --- -------------- --------- --------- ---

----------------------- --- -- -- -
  ------------------- ----- -- ---------
---

总结

在 GraphQL 查询中,如果 totalCount 始终为 0,那么可能是因为我们没有为它指定 resolver 函数。为 totalCount 字段指定 resolver 函数的方法与为其他字段指定 resolver 函数的方法相同。我们只需要在 schema 中为它指定一个 resolver 函数即可。

来源:JavaScript中文网 ,转载请联系管理员! 本文地址:https://www.javascriptcn.com/post/650fb63495b1f8cacd865418


猜你喜欢

相关推荐

    暂无文章