graphql-go / relay-我的节点ID的base64哈希值不是我期望的值

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

我正在与graphql-go一起使用graphql-go/relay库。我正在尝试为我的API编写一些基本测试,并且在使用base64编码机制时遇到了一些麻烦。当我对查看器ID执行简单查询时,查看器编码的ID错误。

我正在对数据库调用进行硬编码以检索ID为1的第一个用户:

func TestGetViewer(t *testing.T) {
  // Empty and fill the db for consistency
  prepDb()

  query := `
    query {
      viewer {
        id
      }
    }
  `

  // The schema contains a viewer entry point that returns a userType:
  // userType = graphql.NewObject(graphql.ObjectConfig{
  //    Name:        "User",
  //    Description: "A user",
  //    Fields: graphql.Fields{
  //      "id": relay.GlobalIDField("User", nil),
  //    },
  // })
  schema := gql.NewSchema(db)

  // graphql.Do is called by graphql.Execute. I'm trying to get 
  // closer to what is actually called in order to debug
  result := graphql.Do(graphql.Params{
    Schema:        schema,
    RequestString: query,
  })

  // The return data from our query
  data := result.Data.(map[string]interface{})

  // The relay.GlobalIDField in our schema should be calling this method
  // under the hood, however, as you'll see it returns something different
  id := relay.ToGlobalID("User", "1")

  // prints map[viewer:map[id:VXNlcjo= username:janedoe]]
  // notice the last character of the id
  fmt.Println(data)

  // prints VXNlcjox
  fmt.Println(id)

graphql.Do返回的内容实际上很接近,但是编码id的最后一个字符与relay.ToGlobalID返回的字符不同。而是显示最后一个用=填充的字符。并且当我尝试运行relay.FromGlobalID("VXNlcjo=")时,它能够确定其typeUser,但是它为ID返回了一个空字符串。而如果我将=替换为x,它将返回正确的对象。

我对Go和这些概念都是陌生的,因此,任何想法或帮助都将不胜感激!

go graphql base64 relay graphql-go
1个回答
0
投票

我是个大人物,在定义我的User结构从数据库检索数据时,忽略编写json字段标签。可以使用大写字母,但由于我同时使用了I和D,因此无法正确解析,并且正在为id传递空字符串。以下已更正:

type User struct {
    ID int `json:"id"`
}

菜鸟错误!但这可能对其他人有帮助。

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