-
Notifications
You must be signed in to change notification settings - Fork 242
/
loadServicesFromRemoteEndpoint.ts
83 lines (75 loc) 路 2.63 KB
/
loadServicesFromRemoteEndpoint.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { GraphQLRequest } from 'apollo-server-types';
import { parse } from 'graphql';
import { Headers, HeadersInit } from 'node-fetch';
import { GraphQLDataSource, GraphQLDataSourceRequestKind } from './datasources/types';
import { SERVICE_DEFINITION_QUERY } from './';
import { ServiceDefinitionUpdate, ServiceEndpointDefinition } from './config';
import { ServiceDefinition } from '@apollo/federation';
export type Service = ServiceEndpointDefinition & {
dataSource: GraphQLDataSource;
};
export async function getServiceDefinitionsFromRemoteEndpoint({
serviceList,
getServiceIntrospectionHeaders,
serviceSdlCache,
}: {
serviceList: Service[];
getServiceIntrospectionHeaders: (
service: ServiceEndpointDefinition,
) => Promise<HeadersInit | undefined>;
serviceSdlCache: Map<string, string>;
}): Promise<ServiceDefinitionUpdate> {
if (!serviceList || !serviceList.length) {
throw new Error(
'Tried to load services from remote endpoints but none provided',
);
}
let isNewSchema = false;
// for each service, fetch its introspection schema
const promiseOfServiceList = serviceList.map(async ({ name, url, dataSource }) => {
if (!url) {
throw new Error(
`Tried to load schema for '${name}' but no 'url' was specified.`);
}
const request: GraphQLRequest = {
query: SERVICE_DEFINITION_QUERY,
http: {
url,
method: 'POST',
headers: new Headers(await getServiceIntrospectionHeaders({ name, url })),
},
};
return dataSource
.process({
kind: GraphQLDataSourceRequestKind.LOADING_SCHEMA,
request,
context: {},
})
.then(({ data, errors }): ServiceDefinition => {
if (data && !errors) {
const typeDefs = data._service.sdl as string;
const previousDefinition = serviceSdlCache.get(name);
// this lets us know if any downstream service has changed
// and we need to recalculate the schema
if (previousDefinition !== typeDefs) {
isNewSchema = true;
}
serviceSdlCache.set(name, typeDefs);
return {
name,
url,
typeDefs: parse(typeDefs),
};
}
throw new Error(errors?.map((e) => e.message).join('\n'));
})
.catch((err) => {
const errorMessage =
`Couldn't load service definitions for "${name}" at ${url}` +
(err && err.message ? ': ' + err.message || err : '');
throw new Error(errorMessage);
});
});
const serviceDefinitions = await Promise.all(promiseOfServiceList);
return { serviceDefinitions, isNewSchema }
}