17a1760afd
## Context As we grow, the messaging scripts are experiencing performance issues forcing us to temporarily disable them on the cloud. While investigating the performance, I have noticed that generating the entity schema (for twentyORM) in the repository is taking ~500ms locally on my Mac M2 so likely more on pods. Caching the entitySchema then! I'm also clarifying naming around schemaVersion and cacheVersions ==> both are renamed workspaceMetadataVersion and migrated to the workspace table (the workspaceCacheVersion table is dropped).
58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import { Plugin } from 'graphql-yoga';
|
|
|
|
export type CacheMetadataPluginConfig = {
|
|
cacheGetter: (key: string) => any;
|
|
cacheSetter: (key: string, value: any) => void;
|
|
operationsToCache: string[];
|
|
};
|
|
|
|
export function useCachedMetadata(config: CacheMetadataPluginConfig): Plugin {
|
|
const computeCacheKey = (serverContext: any) => {
|
|
const workspaceId = serverContext.req.workspace?.id ?? 'anonymous';
|
|
const workspaceMetadataVersion =
|
|
serverContext.req.workspaceMetadataVersion ?? '0';
|
|
const operationName = getOperationName(serverContext);
|
|
|
|
return `graphql:operations:${operationName}:${workspaceId}:${workspaceMetadataVersion}`;
|
|
};
|
|
|
|
const getOperationName = (serverContext: any) =>
|
|
serverContext?.req?.body?.operationName;
|
|
|
|
return {
|
|
onRequest: async ({ endResponse, serverContext }) => {
|
|
if (!config.operationsToCache.includes(getOperationName(serverContext))) {
|
|
return;
|
|
}
|
|
|
|
const cacheKey = computeCacheKey(serverContext);
|
|
const cachedResponse = await config.cacheGetter(cacheKey);
|
|
|
|
if (cachedResponse) {
|
|
const earlyResponse = Response.json(cachedResponse);
|
|
|
|
return endResponse(earlyResponse);
|
|
}
|
|
},
|
|
onResponse: async ({ response, serverContext }) => {
|
|
if (!config.operationsToCache.includes(getOperationName(serverContext))) {
|
|
return;
|
|
}
|
|
|
|
const cacheKey = computeCacheKey(serverContext);
|
|
|
|
const cachedResponse = await config.cacheGetter(cacheKey);
|
|
|
|
if (!cachedResponse) {
|
|
const responseBody = await response.json();
|
|
|
|
if (responseBody.errors) {
|
|
return;
|
|
}
|
|
|
|
config.cacheSetter(cacheKey, responseBody);
|
|
}
|
|
},
|
|
};
|
|
}
|