无需添加字符串即可进行Golang的GraphQL查询。

huangapple go评论77阅读模式
英文:

Make Golang graphql query without adding string

问题

如果我像这样一次性“声明”一个请求,它就能正常工作:

payload := strings.NewReader(`query {
    node(id: "gid://shopify/BulkOperation/2000000011111") {
        ... on BulkOperation {
            url
            partialDataUrl
        }
    }
}`)

然而,gid字段是会变化的,所以我不能像上面那样硬编码它。所以我做了以下操作(queryId是一个变量):

s := `query {
    node(id: "` + queryId + `") {
        ... on BulkOperation {
            url
            partialDataUrl
        }
    }
}`

client := &http.Client{}
req, err := http.NewRequest(method, url, strings.NewReader(s))

结果与硬编码时不一样。似乎gid没有正确添加,导致响应为空。

原始的Python代码是:

data_query = '''
    query {
        node(id: "%s") {
            ... on BulkOperation {
                url
                partialDataUrl
            }
        }
    }
''' % bulkopr_id
英文:

If I "declare" a request in one swoop like this, it works:

payload := strings.NewReader(`query {
		node(id: "gid://shopify/BulkOperation/2000000011111") {
		  ... on BulkOperation {
				url
				partialDataUrl
				}
			}
		}`)

However, the gid field is changing, so I cannot hard-code it like above. So I did the following (queryId is a variable):

s := `query {
		node(id: "` + queryId + `") {
		  ... on BulkOperation {
				url
				partialDataUrl
				}
			}
		}`

	client := &http.Client{}
	req, err := http.NewRequest(method, url, strings.NewReader(s))

And the result is not correct, compared to when I hard code it. Seems like the gid was not added in properly, resulting in empty reponse.

The original Python code is:

data_query = '''
    query {
      node(id: "%s") {
        ... on BulkOperation {
          url
          partialDataUrl
        }
      }
    }
    ''' % bulkopr_id

答案1

得分: 0

发现问题:Shopify需要一些时间来准备查询结果。在我的代码中,我在生成结果后立即调用API,因此结果为空。简单地加上time.Sleep(3*time.Second),响应就不会为空。

英文:

Discover the problem: Shopify needs a little time to prepare the query result. In my code I call the API too quickly after it was generated, therefore the result is empty. Simply put time.Sleep(3*time.Second) and the response will not be empty.

huangapple
  • 本文由 发表于 2022年11月4日 17:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/74314670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定