The base64 hash of my node id is not what I expect

646 Views Asked by At

I am using the graphql-go library along with graphql-go/relay. I am trying to write some basic tests for my API, and am having some trouble with the base64 encoding mechanism. When I execute a simple query for viewer id, the viewer encoded id is wrong.

I am hardcoding the db call to retrieve the first user with 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)

The graphql.Do returns something that is really close, but the last character of the encoded id is different from what is returned by relay.ToGlobalID. It instead shows the last character padded with =. And when I try to run relay.FromGlobalID("VXNlcjo="), it is able to figure out that its type is User, but it returns an empty string for ID. Whereas, if I replace the = with x, it returns the correct object.

I'm new to Go, and to these concepts, so any ideas or help would be greatly appreciated!

1

There are 1 best solutions below

0
On

I'm a big ol' dummy and neglected to write the json field tags when defining my User struct to retrieve data from the db. Single capitalization is okay, but since I capitalize both I and D, it wasn't resolving properly and was passing an empty string for the id. Below is corrected:

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

Rookie mistake! But maybe it can be helpful to others.