UNPKG

1.48 kBPlain TextView Raw
1// Based on https://facebook.github.io/relay/docs/guides-babel-plugin.html#using-other-graphql-implementations
2
3import fetch from 'node-fetch';
4import * as fs from 'fs';
5import * as https from 'https';
6
7import {
8 introspectionQuery,
9} from 'graphql/utilities';
10
11import { ToolError } from 'apollo-codegen-core/lib/errors'
12
13const defaultHeaders = {
14 'Accept': 'application/json',
15 'Content-Type': 'application/json'
16};
17
18export default async function downloadSchema(url: string, outputPath: string, additionalHeaders: { [name: string]: string }, insecure: boolean, method: string) {
19 const headers: { [index: string]: string } = Object.assign(defaultHeaders, additionalHeaders);
20 const agent = insecure ? new https.Agent({ rejectUnauthorized: false }) : undefined;
21
22 let result;
23 try {
24 const response = await fetch(url, {
25 method: method,
26 headers: headers,
27 body: JSON.stringify({ 'query': introspectionQuery }),
28 agent,
29 });
30
31 result = await response.json();
32 } catch (error) {
33 throw new ToolError(`Error while fetching introspection query result: ${error.message}`);
34 }
35
36 if (result.errors) {
37 throw new ToolError(`Errors in introspection query result: ${result.errors}`);
38 }
39
40 const schemaData = result;
41 if (!schemaData.data) {
42 throw new ToolError(`No introspection query result data found, server responded with: ${JSON.stringify(result)}`);
43 }
44
45 fs.writeFileSync(outputPath, JSON.stringify(schemaData, null, 2));
46}