UNPKG

1.43 kBJavaScriptView Raw
1import { isValidPath, parseGraphQLSDL } from '@graphql-toolkit/common';
2
3const FILE_EXTENSIONS = ['.gql', '.gqls', '.graphql', '.graphqls'];
4class GraphQLFileLoader {
5 loaderId() {
6 return 'graphql-file';
7 }
8 async canLoad(pointer, options) {
9 return this.canLoadSync(pointer, options);
10 }
11 canLoadSync(pointer, options) {
12 if (isValidPath(pointer) && options.path && options.fs) {
13 const { resolve, isAbsolute } = options.path;
14 if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
15 const normalizedFilePath = isAbsolute(pointer) ? pointer : resolve(options.cwd || process.cwd(), pointer);
16 const { existsSync } = options.fs;
17 if (existsSync(normalizedFilePath)) {
18 return true;
19 }
20 }
21 }
22 return false;
23 }
24 async load(pointer, options) {
25 return this.loadSync(pointer, options);
26 }
27 loadSync(pointer, options) {
28 const { resolve, isAbsolute } = options.path;
29 const normalizedFilePath = isAbsolute(pointer) ? pointer : resolve(options.cwd || process.cwd(), pointer);
30 const { readFileSync } = options.fs;
31 const rawSDL = readFileSync(normalizedFilePath, 'utf-8').trim();
32 return parseGraphQLSDL(pointer, rawSDL, options);
33 }
34}
35
36export { GraphQLFileLoader };