Apollo客户端使用offsetLimitPagination请求Graphql服务,尽管缓存中已经有可用的数据。
创始人
2024-09-09 11:30:19
0

为了避免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
        }
      }

相关内容

热门资讯

一分钟带你了解!hhpoker... 一分钟带你了解!hhpoker可以开挂吗,wepoker祈福有用吗,都是真的是有挂(有挂秘笈)在进入...
分享给玩家!wepoker辅助... 分享给玩家!wepoker辅助透视软件,wepoker挂,好像真的有挂(竟然有挂)1、分享给玩家!w...
揭秘关于!pokemmo手机脚... 揭秘关于!pokemmo手机脚本,wepoker辅助器激活码,好像真的有挂(了解有挂)1、金币登录送...
玩家亲测!wepoker有人用... 玩家亲测!wepoker有人用过吗,pokerrrr2辅助,竟然存在有挂(有挂技巧)1、玩家可以在线...
科普常识!poker worl... 科普常识!poker world辅助器,哈糖大菠萝攻略,原来是有挂(有挂技巧)1、任何透视是真的假的...
传递经验!pokemmo手机脚... 传递经验!pokemmo手机脚本辅助器,来玩德州破解器,原来是有挂(有挂方略)1、完成有辅助插件,帮...
一分钟揭秘!wepoker辅助... 一分钟揭秘!wepoker辅助透视软件,大菠萝789辅助器下载,总是真的有挂(有挂攻略)1、用户打开...
盘点一款!wepoker祈福有... 盘点一款!wepoker祈福有用吗,werplan外挂,其实有挂(真是有挂)1、操作简单,无需手机版...
分享一款!wepokerplu... 分享一款!wepokerplus作弊,hhpoker德州机器人,本来有挂(有挂秘籍)1、该软件可以轻...
玩家必看攻略!hhpoker有... 玩家必看攻略!hhpoker有后台操控吗,wepoker透视最简单三个步骤,原来存在有挂(有挂头条)...