gpt4 book ai didi

orm - GraphQL, Dataloader, [ORM 与否], 有很多关系理解

转载 作者:行者123 更新时间:2023-12-03 22:39:27 25 4
gpt4 key购买 nike

我第一次使用 Facebook 的数据加载器 ( https://github.com/facebook/dataloader )。

我不明白的是当我有 1 到许多关系 时如何使用它。

这是我的问题的再现: https://enshrined-hydrant.glitch.me

如果您在 Playground 中使用此查询:

query {
persons {
name
bestFriend {
name
}
opponents {
name
}
}
}

你得到值。

但是如果你在这里打开控制台日志: https://glitch.com/edit/#!/enshrined-hydrant 你可以看到这些我想避免的数据库调用:

enter image description here

我的 人类型 是:
type Person {
id: ID!
name: String!
bestFriend: Person
opponents: [Person]
}

我可以将 dataloader 用于 bestFriend: Person ,但我不明白如何将它与 opponents: [Person] 一起使用。

如您所见,解析器必须返回一组值。

您对此有任何提示吗?

最佳答案

您需要创建批处理端点以与数据加载器一起使用 - 它不能自己进行批处理。

例如,您可能需要以下端点:

GET /persons - returns all people
POST /bestFriends, Array<personId>` - returns an array of best friends matchin the corresponding array of `personId`s

然后,您的数据加载器可能如下所示:
function batchedBestFriends(personIds) {
return fetch('/bestFriends', {
method: 'POST',
body: JSON.stringify(personIds))
}).then(response => response.json());
// We assume above that the API returns a straight array of the data.
// If the data was keyed, you could add another accessor such as
// .then(data => data.bestFriends)
}

// The `keys` here will just be the accumulated list of `personId`s from the `load` call in the resolver
const bestFriendLoader = new DataLoader(keys => batchedBestFriends(keys));

现在,您的解析器将类似于:
const PersonType = new GraphQLObjectType({
...
bestFriend: {
type: BestFriendType,
resolve: (person, args, context) => {
return bestFriendLoader.load(person.id);
}
}
});

关于orm - GraphQL, Dataloader, [ORM 与否], 有很多关系理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52165476/

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