我正在关注 React + Relay + GraphQL @ https://facebook.github.io/relay/docs/tutorial.html的教程
我对什么 interface : [nodeInterface] 在 GraphQL 对象定义中的作用感到困惑。
我正在关注 React + Relay + GraphQL @ https://facebook.github.io/relay/docs/tutorial.html的教程
我对什么 interface : [nodeInterface] 在 GraphQL 对象定义中的作用感到困惑。
nodeInterface
仅当客户端(通常是浏览器)请求从初始获取中已经拥有的一块 GraphQL 数据重新获取时,GraphQL 才使用它。
在以下任何一种情况下都会执行重新获取:
this.props.relay.forceFetch()
,这通常发生在程序员认为服务器端的数据可能由于其他外部this.props.relay.setVariable(...)
用户执行某个操作(例如更改要显示的项目数量、图片大小等)时执行,这需要对最初获取的数据进行更改。在重新获取期间,GraphQLnodeInterface
使用(全局)节点 ID调用,nodeInterface
需要检索与该节点 ID 关联的服务器端对象。使用该服务器端对象,GraphQL 服务器可以返回客户端所需的附加/变化数据。
因此,如果从不重新感染初始对象数据,则永远不需要节点 ID。
更多详情请参考:https ://medium.com/@khor/relay-graphql-de-mystifying-node-id-38757121b9c
nodeInterface
执行节点 ID 到服务器端对象解析,因此它总是看起来像:
var {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
var {type, id} = fromGlobalId(globalId);
if (type === 'ClassA') {
// Get ClassA type of instance with id
// E.g.,
return ClassA.find_by_id(id)
} else if (type === 'ClassB') {
return ClassB.find_by_id(id)
}
...
}
)
由于需要重新获取的 GraphQL 类型需要节点 ID,因此在 GraphQL 模式中您需要:
globalIdField
使用关键字请求 GraphQL 在创建 GraphQL 类型的实例时自动生成节点 IDinterface : [nodeInterface]
因此:
var ClassAType = new GraphQLObjectType({
name: 'ClassA',
description: 'A',
fields: () => ({
id: globalIdField('ClassA'),
... other fields ...
}),
interfaces: [nodeInterface],
});