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:
Lucas Bordeau
2024-04-26 17:31:40 +02:00
committed by GitHub
parent 8beec03762
commit 77eece77ea
4 changed files with 43 additions and 2 deletions

View File

@ -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);
}
},
};
}