UNPKG

@graphql-yoga/apollo-managed-federation

Version:

This plugin integrates Apollo Managed Federation into Yoga.

49 lines (48 loc) 2.4 kB
import { createGraphQLError } from 'graphql-yoga'; import { SupergraphSchemaManager, } from '@graphql-tools/federation'; export function useManagedFederation(options = {}) { const { supergraphManager = new SupergraphSchemaManager(options), } = options; const plugin = { onYogaInit({ yoga }) { supergraphManager.on('log', ({ level, message, source }) => { yoga.logger[level](`[ManagedFederation]${source === 'uplink' ? ' <UPLINK>' : ''} ${message}`); }); supergraphManager.on('failure', options.onFailure ?? ((error, delayInSeconds) => { const message = error?.message ?? error; yoga.logger.error(`[ManagedFederation] Failed to load supergraph schema.${message ? ` Last error: ${message}` : ''}`); yoga.logger.info(`[ManagedFederation] No failure handler provided. Retrying in ${delayInSeconds}s.`); supergraphManager.start(delayInSeconds); })); supergraphManager.start(); }, onPluginInit({ setSchema }) { if (supergraphManager.schema) { setSchema(supergraphManager.schema); } else { // Wait for the first schema to be loaded before before allowing requests to be parsed // We can then remove the onRequestParse hook to avoid async cost on every request const waitForInitialization = new Promise((resolve, reject) => { const onFailure = (err) => { reject(createGraphQLError('Supergraph failed to load', { originalError: err instanceof Error ? err : null, })); }; supergraphManager.once('failure', onFailure); supergraphManager.once('schema', schema => { setSchema(schema); supergraphManager.off('failure', onFailure); resolve(); plugin.onRequestParse = undefined; }); }); plugin.onRequestParse = async () => { await waitForInitialization; }; } supergraphManager.on('schema', setSchema); }, }; return plugin; }