@matters/apollo-response-cache
Version:
Caching and invalidation mechanisms (plugins, directives) of Apollo GraphQL
44 lines (43 loc) • 1.15 kB
JavaScript
import { CACHE_KEY_PREFIX_FQC, CACHE_KEY_PREFIX_NODE_FQC } from './enums.js';
/**
* Generate cache key of Node and FQC hashes array mapping
*
* e.g. ['Article', 18] -> 'node-fqcs:Article:18'
*/
export const toNodeFQCKey = (node) => {
return `${CACHE_KEY_PREFIX_NODE_FQC}:${node.type}:${node.id}`;
};
/**
* Record Node:FQC mapping
*
*/
export const recordNodeFQCMapping = ({ nodeFQCKeys, fqcKey, ttl, redis, }) => {
try {
nodeFQCKeys.forEach((cacheKey) => {
redis.sadd(cacheKey, fqcKey);
redis.expire(cacheKey, ttl);
});
}
catch (error) {
console.warn(error);
}
};
/**
* Invalidate full query caches by the given related node keys
*/
export const invalidateFQC = async ({ node, redis, }) => {
try {
const key = toNodeFQCKey(node);
const hashes = await redis.smembers(key);
hashes.map(async (hash) => {
await redis
.pipeline()
.del(`${CACHE_KEY_PREFIX_FQC}${hash}`)
.srem(key, hash)
.exec();
});
}
catch (error) {
console.warn(error);
}
};