UNPKG

@matters/apollo-response-cache

Version:

Caching and invalidation mechanisms (plugins, directives) of Apollo GraphQL

44 lines (43 loc) 2.17 kB
import { defaultFieldResolver } from 'graphql'; import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils'; import { toNodeFQCKey } from '../utils.js'; export const logCacheDirective = (directiveName = 'logCache') => ({ typeDef: `directive @${directiveName}(type: String! identifier: String = "id") on FIELD_DEFINITION`, transformer: (schema, options) => { return mapSchema(schema, { [MapperKind.OBJECT_FIELD]: (fieldConfig) => { const directive = getDirective(schema, fieldConfig, directiveName)?.[0]; if (directive) { const { resolve = defaultFieldResolver } = fieldConfig; fieldConfig.resolve = async (source, args, context, info) => { const result = await resolve(source, args, context, info); const { type, identifier } = directive; const { __nodeFQCKeySet } = context; if (!__nodeFQCKeySet) { return result; } const nodes = Array.isArray(result) ? result : [result]; const { typeResolver, idResolver } = options; nodes.forEach((node) => { const nodeType = typeResolver ? typeResolver(type, node) : type; const nodeId = idResolver ? idResolver(type, node) : node[identifier] || node['id'] || node['_id']; if (!nodeType || !nodeId) { return; } try { __nodeFQCKeySet.add(toNodeFQCKey({ type: nodeType, id: nodeId })); } catch (error) { console.warn(error); } }); return result; }; return fieldConfig; } }, }); }, });