UNPKG

3.42 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5const utils = require('@graphql-tools/utils');
6const crossFetch = require('cross-fetch');
7const graphqlTagPluck = require('@graphql-tools/graphql-tag-pluck');
8const graphql = require('graphql');
9
10// github:owner/name#ref:path/to/file
11function extractData(pointer) {
12 const [repo, file] = pointer.split('#');
13 const [owner, name] = repo.split(':')[1].split('/');
14 const [ref, path] = file.split(':');
15 return {
16 owner,
17 name,
18 ref,
19 path,
20 };
21}
22/**
23 * This loader loads a file from GitHub.
24 *
25 * ```js
26 * const typeDefs = await loadTypedefs('github:githubUser/githubRepo#branchName:path/to/file.ts', {
27 * loaders: [new GithubLoader()],
28 * token: YOUR_GITHUB_TOKEN,
29 * })
30 * ```
31 */
32class GithubLoader {
33 async canLoad(pointer) {
34 return typeof pointer === 'string' && pointer.toLowerCase().startsWith('github:');
35 }
36 canLoadSync() {
37 return false;
38 }
39 async load(pointer, options) {
40 if (!(await this.canLoad(pointer))) {
41 return [];
42 }
43 const { owner, name, ref, path } = extractData(pointer);
44 const request = await crossFetch.fetch('https://api.github.com/graphql', {
45 method: 'POST',
46 headers: {
47 'Content-Type': 'application/json; charset=utf-8',
48 Authorization: `bearer ${options.token}`,
49 },
50 body: JSON.stringify({
51 query: `
52 query GetGraphQLSchemaForGraphQLtools($owner: String!, $name: String!, $expression: String!) {
53 repository(owner: $owner, name: $name) {
54 object(expression: $expression) {
55 ... on Blob {
56 text
57 }
58 }
59 }
60 }
61 `,
62 variables: {
63 owner,
64 name,
65 expression: ref + ':' + path,
66 },
67 operationName: 'GetGraphQLSchemaForGraphQLtools',
68 }),
69 });
70 const response = await request.json();
71 let errorMessage = null;
72 if (response.errors && response.errors.length > 0) {
73 errorMessage = response.errors.map((item) => item.message).join(', ');
74 }
75 else if (!response.data) {
76 errorMessage = response;
77 }
78 if (errorMessage) {
79 throw new Error('Unable to download schema from github: ' + errorMessage);
80 }
81 const content = response.data.repository.object.text;
82 if (/\.(gql|graphql)s?$/i.test(path)) {
83 return [utils.parseGraphQLSDL(pointer, content, options)];
84 }
85 if (/\.json$/i.test(path)) {
86 return [utils.parseGraphQLJSON(pointer, content, options)];
87 }
88 if (path.endsWith('.tsx') || path.endsWith('.ts') || path.endsWith('.js') || path.endsWith('.jsx')) {
89 const sources = await graphqlTagPluck.gqlPluckFromCodeString(pointer, content, options.pluckConfig);
90 return sources.map(source => ({
91 location: pointer,
92 document: graphql.parse(source, options),
93 }));
94 }
95 throw new Error(`Invalid file extension: ${path}`);
96 }
97 loadSync() {
98 throw new Error('Loader GitHub has no sync mode');
99 }
100}
101
102exports.GithubLoader = GithubLoader;