UNPKG

@envelop/apollo-federation

Version:

This plugin integrates Apollo Federation Gateway into Envelop.

68 lines (67 loc) 3.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useApolloFederation = void 0; const graphql_1 = require("graphql"); const apollo_server_caching_1 = require("apollo-server-caching"); const new_cache_policy_js_1 = require("./new-cache-policy.js"); const useApolloFederation = (options) => { const { gateway, cache = new apollo_server_caching_1.InMemoryLRUCache(), logger = console, metrics = Object.create(null), overallCachePolicy = (0, new_cache_policy_js_1.newCachePolicy)(), } = options; let schemaHash; const documentSourceMap = new WeakMap(); return { onPluginInit({ setSchema }) { if (gateway.schema) { setSchema(gateway.schema); } else { logger.warn(`ApolloGateway doesn't have the schema loaded. Please make sure ApolloGateway is loaded with .load() method. Otherwise this plugin might not work consistently, especially if you are using ApolloServer.`); gateway.load(); } gateway.onSchemaLoadOrUpdate(({ apiSchema, coreSupergraphSdl = (0, graphql_1.printSchema)(apiSchema) }) => { setSchema(apiSchema); schemaHash = (coreSupergraphSdl || (0, graphql_1.printSchema)(apiSchema)); }); }, onParse({ params: { source } }) { const key = source instanceof graphql_1.Source ? source.body : source; return ({ result }) => { if (!result || result instanceof Error) return; documentSourceMap.set(result, key); }; }, onExecute({ args, setExecuteFn }) { let documentStr = documentSourceMap.get(args.document); if (documentStr == null) { documentStr = (0, graphql_1.print)(args.document); documentSourceMap.set(args.document, documentStr); } const operation = (0, graphql_1.getOperationAST)(args.document, args.operationName ?? undefined); if (!operation) { throw new Error(`Operation ${args.operationName || ''} cannot be found in ${documentStr}`); } setExecuteFn(function federationExecutor() { return gateway.executor({ document: args.document, request: { query: documentStr, operationName: args.operationName ?? undefined, variables: args.variableValues ?? undefined, }, overallCachePolicy, operationName: args.operationName ?? null, cache, context: args.contextValue, queryHash: documentStr, logger, metrics, source: documentStr, operation, schema: args.schema, schemaHash, }); }); }, }; }; exports.useApolloFederation = useApolloFederation;