Skip to content

Commit eb80821

Browse files
committedSep 29, 2021
enhance(load-files): return DocumentNode if it is an SDL
1 parent 70a30c8 commit eb80821

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed
 

‎.changeset/smooth-planets-tan.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@graphql-tools/load-files': minor
3+
---
4+
5+
enhance(load-files): return DocumentNode if it is an SDL

‎packages/load-files/src/index.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import globby, { sync as globbySync, GlobbyOptions } from 'globby';
22
import unixify from 'unixify';
33
import { extname } from 'path';
44
import { statSync, readFileSync, promises as fsPromises } from 'fs';
5+
import { DocumentNode } from '@apollo/client/core';
6+
import { parse } from 'graphql';
57

68
const { readFile, stat } = fsPromises;
79

@@ -157,7 +159,8 @@ export function loadFilesSync<T = any>(
157159
const extractedExport = extractExports(fileExports);
158160
return extractedExport;
159161
} else {
160-
return readFileSync(path, { encoding: 'utf-8' });
162+
const maybeSDL = readFileSync(path, { encoding: 'utf-8' });
163+
return tryToParse(maybeSDL);
161164
}
162165
})
163166
.filter(v => v);
@@ -237,7 +240,8 @@ export async function loadFiles(
237240
const extractedExport = extractExports(fileExports);
238241
return extractedExport;
239242
} else {
240-
return readFile(path, { encoding: 'utf-8' });
243+
const maybeSDL = await readFile(path, { encoding: 'utf-8' });
244+
return tryToParse(maybeSDL);
241245
}
242246
})
243247
);
@@ -247,3 +251,11 @@ function isIndex(path: string, extensions: string[] = []): boolean {
247251
const IS_INDEX = /(\/|\\)index\.[^\/\\]+$/i; // (/ or \) AND `index.` AND (everything except \ and /)(end of line)
248252
return IS_INDEX.test(path) && extensions.some(ext => path.endsWith(formatExtension(ext)));
249253
}
254+
255+
function tryToParse(maybeSDL: string): string | DocumentNode {
256+
try {
257+
return parse(maybeSDL);
258+
} catch (e) {
259+
return maybeSDL;
260+
}
261+
}

1 commit comments

Comments
 (1)
Please sign in to comment.