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