Apollo服务器端缓存:缓存的键值是什么?
创始人
2024-09-09 09:00:58
0

在Apollo服务器中,缓存的键值(cache key)是由query和variables两个属性决定的。query属性表示查询语句的字符串,variables属性表示查询语句所需的变量,两者合并起来作为缓存的键值。

以下示例代码演示了如何使用实际查询和变量来生成唯一的缓存键值。

import { ApolloServer } from 'apollo-server-express';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
import express from 'express';
import schema from './schema';

const app = express();

const httpLink = createHttpLink({
  uri: 'https://api.example.com/graphql',
  fetch: fetch,
});

const cache = new InMemoryCache();

const server = new ApolloServer({
  schema,
  cache,
  link: httpLink,
  context: ({ req }) => ({
    headers: req.headers,
  }),
  cacheControl: {
    defaultMaxAge: 86400,
  },
  plugins: [{
    requestDidStart(requestContext) {
      const query = requestContext.request.query;
      const variables = JSON.stringify(requestContext.request.variables);
      const cacheKey = `${query}:${variables}`;
      requestContext.context.cacheKey = cacheKey;
      return {
        willSendResponse(requestContext) {
          const { cacheKey } = requestContext.context;
          if (cacheKey) {
            const { response, cache } = requestContext;
            const { data } = response;
            cache.set(cacheKey, data);
          }
        },
      };
    },
  }],
});

server.applyMiddleware({
  app,
});

app.listen({ port: 4000 }, () =>
  console.log(`� Server ready at http://localhost:4000${server.graphqlPath}`)
);

在上面的示例代码中,我们使用了Apollo的requestDidStart插件,在请求开始时获取query和variables,并将两者合并成一个唯一的缓存键值(cache key),存储在请求上下文中,供后面使用。

然后

相关内容

热门资讯

截至发稿!微乐小程序免费黑科技... 您好,微乐自建房免费脚本哪个最好用这款游戏可以开挂的,确实是有挂的,需要了解加去威信【4852750...
九分钟透视!微乐小程序免费黑科... 九分钟透视!微乐小程序免费黑科技,微乐福建辅助器(开挂)其实存在有挂(2026)1、实时微乐小程序免...
现场直击!微乐小程序免费黑科技... 现场直击!微乐小程序免费黑科技,微乐斗地主有挂吗(透视)竟然有挂(哔哩哔哩);1、微乐小程序免费黑科...
第八分钟工具!微乐小程序黑科技... 第八分钟工具!微乐小程序黑科技,微信小程序微乐辅助免费(开挂)果然有挂(2026)1、操作简单,无需...
黑科技攻略!微乐小程序免费黑科... 黑科技攻略!微乐小程序免费黑科技,微信小程序微乐安徽辅助(透视)一直是真的挂(哔哩哔哩)该软件可以轻...
9分钟开挂!微乐小程序免费黑科... 9分钟开挂!微乐小程序免费黑科技,微乐麻将自建房app(开挂)其实存在有挂(2026)1)微乐小程序...
4分钟教程!微乐小程序免费黑科... 您好,微乐小程序免费黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
为了进一步!微乐小程序免费黑科... 为了进一步!微乐小程序免费黑科技,淘宝的微乐辅助是真的吗(透视)确实真的是有挂(哔哩哔哩)1、进入游...
第1分钟插件!微乐小程序黑科技... 第1分钟插件!微乐小程序黑科技,微乐江西小程序辅助器免费(开挂)都是真的有挂(2026)一、微乐小程...
透视免费!微乐小程序黑科技,微... 透视免费!微乐小程序黑科技,微乐小程序免费黑科技下载(透视)确实真的有挂(哔哩哔哩)该软件可以轻松地...