我尝试使用中继实现连接,所有节点的 ID 都相同

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

我使用 graphql 编写了一个非常简单的模式,但边缘中的所有 ID 都相同。

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

我在 github 上发布了具体细节,这里是 link

将以下代码粘贴到浏览器控制台

atob('SW1hZ2U6')

你会发现id的值是"Image:".

表示(new MyImages()).getAll()获取的记录的所有id 属性 为空。

return 联合 ID 或者我建议您将图像定义为 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],
});

因此,globalIdField 期望您的对象有一个名为 'id' 的字段。然后它获取您传递给 globalIdField 的字符串并添加一个“:”和您的对象的 ID 以创建其全局唯一 ID。

如果您的对象没有一个名为 'id' 的字段,那么它不会追加它,您所有的 globalIdField 将只是您传入的字符串和“:”。所以它们不会是独一无二的,它们都是一样的。

您可以将第二个参数传递给 globalIdField,这是一个获取您的对象的函数,returns一个 id 供 globalIdField 使用。因此,假设您的对象的 id 字段实际上称为“_id”(感谢 Mongo!)。您可以这样调用 globalIdField:

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

给你。 Relay 享受的唯一 ID。

这是graphql-relay-js中相关source-code的link:https://github.com/graphql/graphql-relay-js/blob/master/src/node/node.js#L110