在另一个查询中重用从一个查询缓存的数据

Reusing data cached from one query in another

给定一个简单的 graphql 模式,如下所示:

type Contact {
    id: ID!
    name: String
}

type Query {
    RecentContacts: [Contact]
    Contact(id: ID!): Contact
}

如果我查询最近的联系人:

const GET_RECENT_CONTACTS = gql`
    query RecentContacts {
        RecentContacts {
          id
          name
        }
    }`

<Query client={client} query={GET_RECENT_CONTACTS}>
    {({loading, error, data}) => { /* etc... */ }}
</Query>

并接收数据,例如id 为 1 和 2 的联系人,缓存如下:

ROOT_QUERY
    RecentContacts: [Contact]
        0:  Contact:1
              id: 1
              name: Jack
        1:  Contact:2
              id: 2
              name: Jill

有没有办法让 Apollo 知道它可以使用已缓存的条目来查询 Contact(id: 1)Contact(id: 2) 而无需再次发出网络请求来取回已经存在的数据在缓存中?

具体来说,我希望这个查询在 RecentContacts 被查询后不必发出网络请求,因为它需要的数据已经在缓存中(尽管是从调用不同的查询):

const GET_CONTACT = gql`
    query Contact($id: ID!){
        Contact(id: $id){
          id
          name
        }
    }

<Query client={client} query={GET_CONTACT} variables={{id: 1}}>
    {({loading, error, data}) => {/* etc... */}}
</Query>

您可以使用 cache redirects 来做到这一点。以下是修改后的文档中的示例以适用于您的架构:

import { InMemoryCache } from 'apollo-cache-inmemory';

const cache = new InMemoryCache({
  cacheRedirects: {
    Query: {
      User: (_, args, { getCacheKey }) =>
        getCacheKey({ __typename: 'User', id: args.id })
    },
  },
});