Apollo Stack 是否像 Relay 的节点接口一样支持全局对象识别?

Does Apollo Stack support global object identification like the node interface of Relay?

我对 Apollo Stack 和 Relay 都很陌生。我试图在他们之间做出选择来投入我的时间。读完这本书后 Learning GraphQL and Relay,我转向 Apollo 了解它所提供的内容,但目前互联网上的资源不多。

我最近有这个问题但找不到答案:Apollo 支持 global object identification 就像 Relay 支持节点接口一样吗?如果没有,它是否有任何替代解决方案来支持全局对象识别?

!

它目前的工作方式(apollo-client 的 0.5 版)是使用 ApolloClient 构造函数接受的 dataIdFromObject 函数。

如果所有节点都有一个 id 字段,并且它们在所有节点中都是唯一的(例如,在 Graphcool,我们使用 this library 生成唯一的 ID):

import ApolloClient from 'apollo-client';

const client = new ApolloClient({
  dataIdFromObject: o => o.id
});

您必须确保在每个要规范化的查询中包含 id 字段。

如果您的 ID 只是每种类型的唯一,您可以将它们与 __typename 组合以创建唯一标识符:

const client = new ApolloClient({
  dataIdFromObject: (result) => {
    if (result.id && result.__typename) {
      return result.__typename + result.id;
    }

    // Make sure to return null if this object doesn't have an ID
    return null;
  },
});

代码取自official Apollo documentation

apollo-client v2 中,您必须将 dataIdFromObject 传递给 InMemoryCache 实例。

import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import ApolloClient from 'apollo-client';

const client = new ApolloClient({
  link: new HttpLink(),
  cache: new InMemoryCache({
    dataIdFromObject: object => object.id,
  }),
});