gpt4 book ai didi

relayjs - Relay中的nodeInterface、nodeField和nodeDefinitions是什么?

转载 作者:行者123 更新时间:2023-12-01 00:33:55 26 4
gpt4 key购买 nike

我目前正在做 facebook relayjs 教程,我需要帮助理解教程的这一部分,它指出

Next, let's define a node interface and type. We need only provide a way for Relay to map from an object to the GraphQL type associated with that object, and from a global ID to the object it points to


const {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
const {type, id} = fromGlobalId(globalId);
if (type === 'Game') {
return getGame(id);
} else if (type === 'HidingSpot') {
return getHidingSpot(id);
} else {
return null;
}
},
(obj) => {
if (obj instanceof Game) {
return gameType;
} else if (obj instanceof HidingSpot) {
return hidingSpotType;
} else {
return null;
}
}
);

在 nodeDefinition 的第一个参数中,它的 globalId 是从哪里得到的? Game 和 HidingSpot 是 GraphQLSchema 上的名称吗?这个 'const {type, id} = fromGlobalId(globalId);' 是什么意思做?还有什么是第二个论点?我需要帮助理解 nodeDefinitions,不知何故我在官方文档上找不到 nodeDefinitions。谢谢你。

最佳答案

如果您正在编写没有 Relay 的 GraphQL 服务器,您将在 Query 类型上定义许多入口点,例如:

type Query {
picture(id: Int!): Picture
user(id: Int!): User
...etc
}

所以当你想得到一个用户时,你可以很容易地得到它,因为 user可用作图表的入口点。当您为您的页面/屏幕构建查询时,它通常会有几个级别的深度,您可能会去 user -> followers -> pictures .

有时您希望能够仅重新获取部分查询,也许您正在通过连接进行分页,或者您已经运行了突变。 Relay 的 Node 接口(interface)的作用是为您提供一种标准方法来获取通过全局唯一 ID 实现它的任何类型。 Relay 能够在其查询中识别此类节点,并在可能的情况下使用它们来提高重新获取和分页的效率。我们将节点类型添加到根查询类型:
type Query {
picture(id: Int!): Picture
user(id: Int!): User
...etc
node(id: ID!): Node
}

现在为 nodeDefinitions .本质上,这个函数让我们定义了两件事:
  • 如何返回给定其 globalId 的对象。
  • 如何返回给定对象的类型。

  • 第一个用于获取节点字段的 ID 参数并使用它来解析对象。第二个允许您的 GraphQL 服务器计算返回的对象类型 - 这是必要的,以便我们能够在查询节点时定义特定类型的片段,以便我们可以实际获取我们想要的数据。没有这个,我们就无法成功执行这样的查询:
    query Test {
    node(id: 'something') {
    ...fragment on Picture {
    url
    }
    ...fragment on User {
    username
    }
    }
    }

    关于relayjs - Relay中的nodeInterface、nodeField和nodeDefinitions是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42576581/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com