在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),存储在请求上下文中,供后面使用。
然后