-
-
Notifications
You must be signed in to change notification settings - Fork 804
/
index.ts
211 lines (189 loc) · 6.29 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { existsSync, promises as fsPromises, readFileSync } from 'fs';
import { isAbsolute, resolve } from 'path';
import { env, cwd as processCwd } from 'process';
import type { GlobbyOptions } from 'globby';
import globby from 'globby';
import unixify from 'unixify';
import { processImport } from '@graphql-tools/import';
import {
asArray,
BaseLoaderOptions,
isValidPath,
Loader,
parseGraphQLSDL,
Source,
} from '@graphql-tools/utils';
const { readFile, access } = fsPromises;
const FILE_EXTENSIONS = ['.gql', '.gqls', '.graphql', '.graphqls'];
/**
* Additional options for loading from a GraphQL file
*/
export interface GraphQLFileLoaderOptions extends BaseLoaderOptions {
/**
* Set to `true` to disable handling `#import` syntax
*/
skipGraphQLImport?: boolean;
}
function isGraphQLImportFile(rawSDL: string) {
const trimmedRawSDL = rawSDL.trim();
return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');
}
function createGlobbyOptions(options: GraphQLFileLoaderOptions): GlobbyOptions {
return { absolute: true, ...options, ignore: [] };
}
const buildIgnoreGlob = (path: string) => `!${path}`;
/**
* This loader loads documents and type definitions from `.graphql` files.
*
* You can load a single source:
*
* ```js
* const schema = await loadSchema('schema.graphql', {
* loaders: [
* new GraphQLFileLoader()
* ]
* });
* ```
*
* Or provide a glob pattern to load multiple sources:
*
* ```js
* const schema = await loadSchema('graphql/*.graphql', {
* loaders: [
* new GraphQLFileLoader()
* ]
* });
* ```
*/
export class GraphQLFileLoader implements Loader<GraphQLFileLoaderOptions> {
async canLoad(pointer: string, options: GraphQLFileLoaderOptions): Promise<boolean> {
if (isValidPath(pointer)) {
if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
const normalizedFilePath = isAbsolute(pointer)
? pointer
: resolve(options.cwd || processCwd(), pointer);
try {
await access(normalizedFilePath);
return true;
} catch {
return false;
}
}
}
return false;
}
canLoadSync(pointer: string, options: GraphQLFileLoaderOptions): boolean {
if (isValidPath(pointer)) {
if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
const normalizedFilePath = isAbsolute(pointer)
? pointer
: resolve(options.cwd || processCwd(), pointer);
return existsSync(normalizedFilePath);
}
}
return false;
}
private _buildGlobs(glob: string, options: GraphQLFileLoaderOptions) {
const ignores = asArray(options.ignore || []);
const globs = [unixify(glob), ...ignores.map(v => buildIgnoreGlob(unixify(v)))];
return globs;
}
async resolveGlobs(glob: string, options: GraphQLFileLoaderOptions) {
if (
!glob.includes('*') &&
(await this.canLoad(glob, options)) &&
!asArray(options.ignore || []).length &&
!options['includeSources']
)
return [glob]; // bypass globby when no glob character, can be loaded, no ignores and source not requested. Fixes problem with pkg and passes ci tests
const globs = this._buildGlobs(glob, options);
const result = await globby(globs, createGlobbyOptions(options));
return result;
}
resolveGlobsSync(glob: string, options: GraphQLFileLoaderOptions) {
if (
!glob.includes('*') &&
this.canLoadSync(glob, options) &&
!asArray(options.ignore || []).length &&
!options['includeSources']
)
return [glob]; // bypass globby when no glob character, can be loaded, no ignores and source not requested. Fixes problem with pkg and passes ci tests
const globs = this._buildGlobs(glob, options);
const result = globby.sync(globs, createGlobbyOptions(options));
return result;
}
async load(pointer: string, options: GraphQLFileLoaderOptions): Promise<Source[]> {
const resolvedPaths = await this.resolveGlobs(pointer, options);
const finalResult: Source[] = [];
const errors: Error[] = [];
await Promise.all(
resolvedPaths.map(async path => {
if (await this.canLoad(path, options)) {
try {
const normalizedFilePath = isAbsolute(path)
? path
: resolve(options.cwd || processCwd(), path);
const rawSDL: string = await readFile(normalizedFilePath, { encoding: 'utf8' });
finalResult.push(this.handleFileContent(rawSDL, normalizedFilePath, options));
} catch (e: any) {
if (env['DEBUG']) {
console.error(e);
}
errors.push(e);
}
}
}),
);
if (errors.length > 0) {
if (errors.length === 1) {
throw errors[0];
}
throw new AggregateError(
errors,
`Reading from ${pointer} failed ; \n ` + errors.map((e: Error) => e.message).join('\n'),
);
}
return finalResult;
}
loadSync(pointer: string, options: GraphQLFileLoaderOptions): Source[] {
const resolvedPaths = this.resolveGlobsSync(pointer, options);
const finalResult: Source[] = [];
const errors: Error[] = [];
for (const path of resolvedPaths) {
if (this.canLoadSync(path, options)) {
try {
const normalizedFilePath = isAbsolute(path)
? path
: resolve(options.cwd || processCwd(), path);
const rawSDL = readFileSync(normalizedFilePath, { encoding: 'utf8' });
finalResult.push(this.handleFileContent(rawSDL, normalizedFilePath, options));
} catch (e: any) {
if (env['DEBUG']) {
console.error(e);
}
errors.push(e);
}
}
}
if (errors.length > 0) {
if (errors.length === 1) {
throw errors[0];
}
throw new AggregateError(
errors,
`Reading from ${pointer} failed ; \n ` + errors.map((e: Error) => e.message).join('\n'),
);
}
return finalResult;
}
handleFileContent(rawSDL: string, pointer: string, options: GraphQLFileLoaderOptions) {
if (!options.skipGraphQLImport && isGraphQLImportFile(rawSDL)) {
const document = processImport(pointer, options.cwd);
return {
location: pointer,
document,
};
}
return parseGraphQLSDL(pointer, rawSDL, options);
}
}