Fan Jin
Fan Jin

Reputation: 2460

I try to implement a connection using relay and all the node's IDs are the same

I write a really simple schema using graphql, but some how all the IDs in the edges are the same.

{
    "data": {
        "imageList": {
            "id": "SW1hZ2VMaXN0Og==",
            "images": {
                "edges": [
                  {
                      "node": {
                          "id": "SW1hZ2U6",
                          "url": "1.jpg"
                      }
                  },
                  {
                      "node": {
                          "id": "SW1hZ2U6",
                          "url": "2.jpg"
                      }
                  },
                  {
                      "node": {
                          "id": "SW1hZ2U6",
                          "url": "3.jpg"
                      }
                  }
                ]
            }
        }
    }
}

I posted the specific detail on github here's the link.

Upvotes: 0

Views: 802

Answers (2)

Michael Gallagher
Michael Gallagher

Reputation: 96

So, globalIdField expects your object to have a field named 'id'. It then takes the string you pass to globalIdField and adds a ':' and your object's id to create its globally unique id.

If you object doesn't have a field called exactly 'id', then it wont append it, and all your globalIdField will just be the string you pass in and ':'. So they wont be unique, they will all be the same.

There is a second parameter you can pass to globalIdField which is a function that gets your object and returns an id for globalIdField to use. So lets say your object's id field is actually called '_id' (thanks Mongo!). You would call globalIdField like so:

id: globalIdField('Image', image => image._id)

There you go. Unique IDs for Relay to enjoy.

Here is the link to the relevant source-code in graphql-relay-js: https://github.com/graphql/graphql-relay-js/blob/master/src/node/node.js#L110

Upvotes: 8

soonlive
soonlive

Reputation: 1

paste the following code in browser console

atob('SW1hZ2U6')

you will find that the value of id is "Image:".

it means all id property of records fetched by (new MyImages()).getAll() is null.

return union ids or I suggest you define images as GraphQLList

var ImageListType = new GraphQL.GraphQLObjectType({
  name: 'ImageList',
  description: 'A list of images',
  fields: () => ({
    id: Relay.globalIdField('ImageList'),
    images: {
      type: new GraphQLList(ImageType),
      description: 'A collection of images',
      args: Relay.connectionArgs,
      resolve: (_, args) => Relay.connectionFromPromisedArray(
        (new MyImages()).getAll(),
        args
      ),
    },
  }),
  interfaces: [nodeDefinition.nodeInterface],
});

Upvotes: 0

Related Questions