UNPKG

2.59 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5const common = require('@graphql-toolkit/common');
6const crossFetch = require('cross-fetch');
7
8// github:owner/name#ref:path/to/file
9function extractData(pointer) {
10 const [repo, file] = pointer.split('#');
11 const [owner, name] = repo.split(':')[1].split('/');
12 const [ref, path] = file.split(':');
13 return {
14 owner,
15 name,
16 ref,
17 path,
18 };
19}
20class GithubLoader {
21 loaderId() {
22 return 'github-loader';
23 }
24 async canLoad(pointer) {
25 return typeof pointer === 'string' && pointer.toLowerCase().startsWith('github:');
26 }
27 async load(pointer, options) {
28 const { owner, name, ref, path } = extractData(pointer);
29 const request = await crossFetch.fetch('https://api.github.com/graphql', {
30 method: 'POST',
31 headers: {
32 'Content-Type': 'application/json; charset=utf-8',
33 Authorization: `bearer ${options.token}`,
34 },
35 body: JSON.stringify({
36 query: `
37 query GetGraphQLSchemaForGraphQLToolkit($owner: String!, $name: String!, $expression: String!) {
38 repository(owner: $owner, name: $name) {
39 object(expression: $expression) {
40 ... on Blob {
41 text
42 }
43 }
44 }
45 }
46 `,
47 variables: {
48 owner,
49 name,
50 expression: ref + ':' + path,
51 },
52 operationName: 'GetGraphQLSchemaForGraphQLToolkit',
53 }),
54 });
55 const response = await request.json();
56 let errorMessage = null;
57 if (response.errors && response.errors.length > 0) {
58 errorMessage = response.errors.map((item) => item.message).join(', ');
59 }
60 else if (!response.data) {
61 errorMessage = response;
62 }
63 if (errorMessage) {
64 throw new Error('Unable to download schema from github: ' + errorMessage);
65 }
66 const content = response.data.repository.object.text;
67 if (/\.(gql|graphql)s?$/i.test(path)) {
68 return common.parseGraphQLSDL(pointer, content, options);
69 }
70 if (/\.json$/i.test(path)) {
71 return common.parseGraphQLJSON(pointer, content, options);
72 }
73 throw new Error(`Invalid file extension: ${path}`);
74 }
75}
76
77exports.GithubLoader = GithubLoader;