UNPKG

2.77 kBJavaScriptView Raw
1import { parseGraphQLSDL, AggregateError } from '@graphql-tools/utils';
2import { fetch } from '@whatwg-node/fetch';
3import syncFetch from '@ardatan/sync-fetch';
4const DEFAULT_APOLLO_ENDPOINT = 'https://engine-graphql.apollographql.com/api/graphql';
5/**
6 * This loader loads a schema from Apollo Engine
7 */
8export class ApolloEngineLoader {
9 getFetchArgs(options) {
10 return [
11 options.engine.endpoint || DEFAULT_APOLLO_ENDPOINT,
12 {
13 method: 'POST',
14 headers: {
15 'x-api-key': options.engine.apiKey,
16 'apollo-client-name': 'Apollo Language Server',
17 'apollo-client-reference-id': '146d29c0-912c-46d3-b686-920e52586be6',
18 'apollo-client-version': '2.6.8',
19 'Content-Type': 'application/json',
20 Accept: 'application/json',
21 ...options.headers,
22 },
23 body: JSON.stringify({
24 query: SCHEMA_QUERY,
25 variables: {
26 id: options.graph,
27 tag: options.variant,
28 },
29 }),
30 },
31 ];
32 }
33 async canLoad(ptr) {
34 return this.canLoadSync(ptr);
35 }
36 canLoadSync(ptr) {
37 return typeof ptr === 'string' && ptr === 'apollo-engine';
38 }
39 async load(pointer, options) {
40 if (!(await this.canLoad(pointer))) {
41 return [];
42 }
43 const fetchArgs = this.getFetchArgs(options);
44 const response = await fetch(...fetchArgs);
45 const { data, errors } = await response.json();
46 if (errors) {
47 throw new AggregateError(errors, 'Introspection from Apollo Engine failed; \n ' + errors.map((e) => e.message).join('\n'));
48 }
49 const source = parseGraphQLSDL(pointer, data.service.schema.document, options);
50 return [source];
51 }
52 loadSync(pointer, options) {
53 if (!this.canLoadSync(pointer)) {
54 return [];
55 }
56 const fetchArgs = this.getFetchArgs(options);
57 const response = syncFetch(...fetchArgs);
58 const { data, errors } = response.json();
59 if (errors) {
60 throw new AggregateError(errors, 'Introspection from Apollo Engine failed; \n ' + errors.map((e) => e.message).join('\n'));
61 }
62 const source = parseGraphQLSDL(pointer, data.service.schema.document, options);
63 return [source];
64 }
65}
66/**
67 * @internal
68 */
69export const SCHEMA_QUERY = /* GraphQL */ `
70 query GetSchemaByTag($tag: String!, $id: ID!) {
71 service(id: $id) {
72 ... on Service {
73 __typename
74 schema(tag: $tag) {
75 document
76 }
77 }
78 }
79 }
80`;