-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathloadSupergraphSdlFromStorage.ts
110 lines (98 loc) · 2.73 KB
/
loadSupergraphSdlFromStorage.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { fetch, Response } from 'apollo-server-env';
import { GraphQLError } from 'graphql';
import { SupergraphSdlQuery } from './__generated__/graphqlTypes';
// Magic /* GraphQL */ comment below is for codegen, do not remove
export const SUPERGRAPH_SDL_QUERY = /* GraphQL */`#graphql
query SupergraphSdl($apiKey: String!, $ref: String!) {
routerConfig(ref: $ref, apiKey: $apiKey) {
__typename
... on RouterConfigResult {
id
supergraphSdl: supergraphSDL
}
... on FetchError {
code
message
}
}
}
`;
type SupergraphSdlQueryResult =
| SupergraphSdlQuerySuccess
| SupergraphSdlQueryFailure;
interface SupergraphSdlQuerySuccess {
data: SupergraphSdlQuery;
}
interface SupergraphSdlQueryFailure {
data?: SupergraphSdlQuery;
errors: GraphQLError[];
}
const { name, version } = require('../package.json');
const fetchErrorMsg = "An error occurred while fetching your schema from Apollo: ";
export async function loadSupergraphSdlFromStorage({
graphRef,
apiKey,
endpoint,
fetcher,
}: {
graphRef: string;
apiKey: string;
endpoint: string;
fetcher: typeof fetch;
}) {
let result: Response;
try {
result = await fetcher(endpoint, {
method: 'POST',
body: JSON.stringify({
query: SUPERGRAPH_SDL_QUERY,
variables: {
ref: graphRef,
apiKey,
},
}),
headers: {
'apollographql-client-name': name,
'apollographql-client-version': version,
'user-agent': `${name}/${version}`,
'content-type': 'application/json',
},
});
} catch (e) {
throw new Error(fetchErrorMsg + (e.message ?? e));
}
let response: SupergraphSdlQueryResult;
if (result.ok || result.status === 400) {
try {
response = await result.json();
} catch (e) {
// Bad response
throw new Error(fetchErrorMsg + result.status + ' ' + e.message ?? e);
}
if ('errors' in response) {
throw new Error(
[fetchErrorMsg, ...response.errors.map((error) => error.message)].join(
'\n',
),
);
}
} else {
throw new Error(fetchErrorMsg + result.status + ' ' + result.statusText);
}
const { routerConfig } = response.data;
if (routerConfig.__typename === 'RouterConfigResult') {
const {
id,
supergraphSdl,
// messages,
} = routerConfig;
// `supergraphSdl` should not be nullable in the schema, but it currently is
return { id, supergraphSdl: supergraphSdl! };
} else if (routerConfig.__typename === 'FetchError') {
// FetchError case
const { code, message } = routerConfig;
throw new Error(`${code}: ${message}`);
} else {
throw new Error('Programming error: unhandled response failure');
}
}