win*_*ter 6 graphql apollo-client apollo-link-rest
我有以下查询:
const getPage = gql`
query Page($path: String!) {
page(path: $path) @rest(type: "Page", path: "{args.path}") {
blocks @type(name: Block) {
name
posts @type(name: Post) {
body
author
}
}
authors @type(name: Author) {
name
}
}
}
Run Code Online (Sandbox Code Playgroud)
在blocks.posts.author只有一个AuthorId。作者对象包含所有可用的作者。
我想AuthorId用它的对应对象替换/匹配它。是否可以在一个查询中执行此操作?
我也不会介意仅对Author进行单独的查询(提取将被缓存,不会发出新请求),但是我仍然不知道如何通过2个查询来匹配它。
示例API响应
{
blocks: [
{
posts: [
{
id: 1,
title: 'My post',
author: 12,
}
]
}
],
authors: [
{
id: 12,
name: 'John Doe'
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想要的1个查询author在a内post变成完整的作者对象。
小智 0
很好的问题。使用 GraphQL,您可以扩展任何字段并从中选择您想要的确切子字段,因此如果您也在后端使用 GraphQL,这将不是问题。您可以在此处执行一些解决方法:
如果所有 Author 对象都在 Apollo 缓存中,并且您可以访问每个 Author 的 id,则可以使用ApolloClient.readFragment来访问其他属性,如下所示:
const authorId = ...; // the id of the author
const authorInfo = client.readFragment({
id: authorId,
fragment: gql`
fragment AuthorInfo on Author {
id
name
# anything else you want here
}
`,
});
Run Code Online (Sandbox Code Playgroud)
尽管值得注意的是,对于问题中的原始查询,如果您将所有 Author 对象作为查询的属性,则可以仅使用 Javascript 操作从 Author id 转到对象。
const authorId = ...; // the id of the author
data.page.authors.find(author => author.id === authorId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |