如何在 graphql 查询结构中声明变量以使用 Hasura Go 客户端进行分页?

问题描述 投票:0回答:1

使用 Hasura graphql Go 客户端执行分页查询时遇到问题

github.com/hasura/go-graphql-client
但尚未在文档中找到答案。 graphql查询如下(针对这个问题进行了简化):

query ($after: String) {
    entity (first: 10, after: $after) {
        pageInfo {
          hasNextPage
          endCursor
        }
        nodes {
          name
        }
    }
}

Go 代码

type Query struct {
    Entity struct {
        PageInfo struct {
            HasNextPage bool   `graphql:"hasNextPage"`
            EndCursor   string `graphql:"endCursor"`
        } `graphql:"pageInfo"`

        Nodes []struct {
            Name string `graphql:"name"`
        } `graphql:"nodes`
    } `graphql:"entity(first: 10, after: $after)"`
}

var q Query

var after string = ""
var hasNextPage bool = true

variables := map[string]interface{}{
    "after": after,
}

err := client.Query(context.Background(), &q, variables)

问题是我不知道如何声明 $after 变量,并且在执行时会抛出错误

"Failed to parse \"String\": EOF while parsing a value at line 1 column 0"

有人可以帮忙解决这个问题吗?预先感谢。

go graphql hasura
1个回答
0
投票

代码没问题,问题是如果 after 变量(游标 Id)为空或具有与游标不匹配的值,则查询会抛出错误。

所以解决方案是在没有 $after 变量的情况下执行第一个查询,如下所示

type Query struct {
    Entity struct {
        PageInfo struct {
            HasNextPage bool   `graphql:"hasNextPage"`
            EndCursor   string `graphql:"endCursor"`
        } `graphql:"pageInfo"`

        Nodes []struct {
            Name string `graphql:"name"`
        } `graphql:"nodes`
    } `graphql:"entity(first: 10)"`
}

...

variables := map[string]interface{}{}

一旦我们有了正确的 Endcursor 值,我们就可以使用 $after 变量的该值进行后续查询,就像问题中那样

type Query struct {
    Entity struct {
        PageInfo struct {
            HasNextPage bool   `graphql:"hasNextPage"`
            EndCursor   string `graphql:"endCursor"`
        } `graphql:"pageInfo"`

        Nodes []struct {
            Name string `graphql:"name"`
        } `graphql:"nodes`
    } `graphql:"entity(first: 10, after: $after)"`
}

...

variables := map[string]interface{}{
    "after": after,
}

也许有更好的方法可以在不重复代码的情况下做到这一点,但还没有找到。

© www.soinside.com 2019 - 2024. All rights reserved.