为了避免Apollo客户端在缓存中已经有可用数据的情况下还向Graphql服务发出请求,可以采用缓存策略来优化查询。其中,缓存策略有两种类型:缓存优先和网络优先。
缓存优先的策略会首先从缓存中获取数据,如果缓存中没有数据,才会向Graphql服务发出请求;网络优先的策略则会直接向Graphql服务发出请求,然后再将数据存入缓存中。
以下代码演示了如何使用缓存策略来优化查询:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
const httpLink = createHttpLink({
uri: 'https://graphql.example.com',
});
const cache = new InMemoryCache({
/* 设置缓存策略 */
typePolicies: {
Query: {
fields: {
/* 以缓存优先方式获取数据 */
getPosts: {
keyArgs: ['page', 'limit'],
merge(existing = {}, incoming) {
return {
...incoming,
posts: [...(existing.posts || []), ...incoming.posts],
};
},
read(existing, { args: { page, limit } }) {
const allPosts = existing?.posts || [];
const posts = allPosts.slice((page - 1) * limit, page * limit);
return posts.length
? {
...existing,
posts,
}
: undefined;
},
},
},
},
},
});
const apolloClient = new ApolloClient({
link: httpLink,
cache,
});
/* 使用缓存优先策略查询数据 */
apolloClient.query({
query: gql`
query getPosts($page: Int!, $limit: Int!) {
getPosts(page: $page, limit: $limit) {
posts {
id
title
}
}