Add a cache on /metadata (#5189)
In this PR I'm introducing a simple custom graphql-yoga plugin to create a caching mechanism specific to our metadata. The cache key is made of : workspace id + workspace cache version, with this the cache is automatically invalidated each time a change is made on the workspace metadata.
This commit is contained in:
@ -0,0 +1,38 @@
|
||||
import { Plugin } from 'graphql-yoga';
|
||||
|
||||
export function useCachedMetadata(): Plugin {
|
||||
const cache = new Map<string, any>();
|
||||
|
||||
const computeCacheKey = (serverContext: any) => {
|
||||
const workspaceId = serverContext.req.workspace?.id ?? 'anonymous';
|
||||
const cacheVersion = serverContext.req.cacheVersion ?? '0';
|
||||
|
||||
return `${workspaceId}:${cacheVersion}`;
|
||||
};
|
||||
|
||||
return {
|
||||
onRequest: ({ endResponse, serverContext }) => {
|
||||
const cacheKey = computeCacheKey(serverContext);
|
||||
const foundInCache = cache.has(cacheKey);
|
||||
|
||||
if (foundInCache) {
|
||||
const cachedResponse = cache.get(cacheKey);
|
||||
|
||||
const earlyResponse = Response.json(cachedResponse);
|
||||
|
||||
return endResponse(earlyResponse);
|
||||
}
|
||||
},
|
||||
onResponse: async ({ response, serverContext }) => {
|
||||
const cacheKey = computeCacheKey(serverContext);
|
||||
|
||||
const foundInCache = cache.has(cacheKey);
|
||||
|
||||
if (!foundInCache) {
|
||||
const responseBody = await response.json();
|
||||
|
||||
cache.set(cacheKey, responseBody);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user