Introduce createSupergraphManager (#262)

This commit is contained in:
Kamil Kisiela 2022-07-27 17:12:23 +02:00 committed by GitHub
parent e4f11585d1
commit a94fd68503
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'@graphql-hive/client': minor
---
Introduce createSupergraphManager for @apollo/gateway v2

View file

@ -28,6 +28,46 @@ export function createSupergraphSDLFetcher({ endpoint, key }: SupergraphSDLFetch
};
}
export function createSupergraphManager(options: { pollIntervalInMs?: number } & SupergraphSDLFetcherOptions) {
const pollIntervalInMs = options.pollIntervalInMs ?? 30_000;
const fetchSupergraph = createSupergraphSDLFetcher({ endpoint: options.endpoint, key: options.key });
let timer: ReturnType<typeof setTimeout> | null = null;
return {
async initialize(hooks: { update(supergraphSdl: string): void }): Promise<{
supergraphSdl: string;
cleanup?: () => Promise<void>;
}> {
const initialResult = await fetchSupergraph();
function poll() {
timer = setTimeout(async () => {
try {
const result = await fetchSupergraph();
if (result.supergraphSdl) {
hooks.update?.(result.supergraphSdl);
}
} catch (error) {
console.error(`Failed to update supergraph: ${error instanceof Error ? error.message : error}`);
}
poll();
}, pollIntervalInMs);
}
poll();
return {
supergraphSdl: initialResult.supergraphSdl,
cleanup: async () => {
if (timer) {
clearTimeout(timer);
}
},
};
},
};
}
export function hiveApollo(clientOrOptions: HiveClient | HivePluginOptions): ApolloServerPlugin {
const hive = isHiveClient(clientOrOptions)
? clientOrOptions

View file

@ -1,5 +1,5 @@
export type { HivePluginOptions, HiveClient } from './internal/types';
export { useHive } from './envelop';
export { hiveApollo, createSupergraphSDLFetcher } from './apollo';
export { hiveApollo, createSupergraphSDLFetcher, createSupergraphManager } from './apollo';
export { createSchemaFetcher, createServicesFetcher } from './gateways';
export { createHive } from './client';