UNPKG

@graphql-mesh/plugin-live-query

Version:
80 lines (76 loc) 3.9 kB
import { useLiveQuery } from '@envelop/live-query'; import { InMemoryLiveQueryStore, defaultResourceIdentifierNormalizer } from '@n1ru4l/in-memory-live-query-store'; import { getInterpolatedStringFactory, stringInterpolator } from '@graphql-mesh/string-interpolation'; import { getOperationAST, TypeInfo, visit, visitWithTypeInfo } from 'graphql'; import { process as process$1 } from '@graphql-mesh/cross-helpers'; function useInvalidateByResult(params) { const liveQueryInvalidationFactoryMap = new Map(); params.invalidations.forEach(liveQueryInvalidation => { const rawInvalidationPaths = liveQueryInvalidation.invalidate; const factories = rawInvalidationPaths.map(rawInvalidationPath => getInterpolatedStringFactory(rawInvalidationPath)); liveQueryInvalidationFactoryMap.set(liveQueryInvalidation.field, factories); }); return { onExecute() { return { onExecuteDone({ args: executionArgs, result }) { const { schema, document, operationName, rootValue, contextValue } = executionArgs; const operationAST = getOperationAST(document, operationName); if (!operationAST) { throw new Error(`Operation couldn't be found`); } const typeInfo = new TypeInfo(schema); visit(operationAST, visitWithTypeInfo(typeInfo, { Field: () => { const parentType = typeInfo.getParentType(); const fieldDef = typeInfo.getFieldDef(); const path = `${parentType.name}.${fieldDef.name}`; if (liveQueryInvalidationFactoryMap.has(path)) { const invalidationPathFactories = liveQueryInvalidationFactoryMap.get(path); const invalidationPaths = invalidationPathFactories.map(invalidationPathFactory => invalidationPathFactory({ root: rootValue, context: contextValue, env: process.env, result, })); params.pubsub.publish('live-query:invalidate', invalidationPaths); } }, })); }, }; }, }; } function useMeshLiveQuery(options) { options.logger.debug(`Creating Live Query Store`); const liveQueryStore = new InMemoryLiveQueryStore({ buildResourceIdentifier: options.resourceIdentifier != null ? function resourceIdentifierFactory({ typename, id }) { return stringInterpolator.parse(options.resourceIdentifier, { typename, id, env: process$1.env, }); } : defaultResourceIdentifierNormalizer, includeIdentifierExtension: options.includeIdentifierExtension != null ? options.includeIdentifierExtension : process$1.env.DEBUG === '1', idFieldName: options.idFieldName, indexBy: options.indexBy, }); options.pubsub.subscribe('live-query:invalidate', (identifiers) => liveQueryStore.invalidate(identifiers)); return { onPluginInit({ addPlugin }) { var _a; addPlugin(useLiveQuery({ liveQueryStore })); if ((_a = options.invalidations) === null || _a === void 0 ? void 0 : _a.length) { addPlugin(useInvalidateByResult({ pubsub: options.pubsub, invalidations: options.invalidations, logger: options.logger, })); } }, }; } export default useMeshLiveQuery;