UNPKG

5.62 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.JsonFileLoader = void 0;
4const tslib_1 = require("tslib");
5const utils_1 = require("@graphql-tools/utils");
6const path_1 = require("path");
7const fs_1 = require("fs");
8const process_1 = require("process");
9const globby_1 = tslib_1.__importDefault(require("globby"));
10const unixify_1 = tslib_1.__importDefault(require("unixify"));
11const { readFile, access } = fs_1.promises;
12const FILE_EXTENSIONS = ['.json'];
13function createGlobbyOptions(options) {
14 return { absolute: true, ...options, ignore: [] };
15}
16const buildIgnoreGlob = (path) => `!${path}`;
17/**
18 * This loader loads documents and type definitions from JSON files.
19 *
20 * The JSON file can be the result of an introspection query made against a schema:
21 *
22 * ```js
23 * const schema = await loadSchema('schema-introspection.json', {
24 * loaders: [
25 * new JsonFileLoader()
26 * ]
27 * });
28 * ```
29 *
30 * Or it can be a `DocumentNode` object representing a GraphQL document or type definitions:
31 *
32 * ```js
33 * const documents = await loadDocuments('queries/*.json', {
34 * loaders: [
35 * new GraphQLFileLoader()
36 * ]
37 * });
38 * ```
39 */
40class JsonFileLoader {
41 async canLoad(pointer, options) {
42 if ((0, utils_1.isValidPath)(pointer)) {
43 if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
44 const normalizedFilePath = (0, path_1.isAbsolute)(pointer) ? pointer : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), pointer);
45 try {
46 await access(normalizedFilePath);
47 return true;
48 }
49 catch (_a) {
50 return false;
51 }
52 }
53 }
54 return false;
55 }
56 canLoadSync(pointer, options) {
57 if ((0, utils_1.isValidPath)(pointer)) {
58 if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
59 const normalizedFilePath = (0, path_1.isAbsolute)(pointer) ? pointer : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), pointer);
60 return (0, fs_1.existsSync)(normalizedFilePath);
61 }
62 }
63 return false;
64 }
65 _buildGlobs(glob, options) {
66 const ignores = (0, utils_1.asArray)(options.ignore || []);
67 const globs = [(0, unixify_1.default)(glob), ...ignores.map(v => buildIgnoreGlob((0, unixify_1.default)(v)))];
68 return globs;
69 }
70 async resolveGlobs(glob, options) {
71 const globs = this._buildGlobs(glob, options);
72 const result = await (0, globby_1.default)(globs, createGlobbyOptions(options));
73 return result;
74 }
75 resolveGlobsSync(glob, options) {
76 const globs = this._buildGlobs(glob, options);
77 const result = globby_1.default.sync(globs, createGlobbyOptions(options));
78 return result;
79 }
80 async load(pointer, options) {
81 const resolvedPaths = await this.resolveGlobs(pointer, options);
82 const finalResult = [];
83 const errors = [];
84 await Promise.all(resolvedPaths.map(async (path) => {
85 if (await this.canLoad(path, options)) {
86 try {
87 const normalizedFilePath = (0, path_1.isAbsolute)(path) ? path : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), path);
88 const rawSDL = await readFile(normalizedFilePath, { encoding: 'utf8' });
89 finalResult.push(this.handleFileContent(normalizedFilePath, rawSDL, options));
90 }
91 catch (e) {
92 if (process_1.env['DEBUG']) {
93 console.error(e);
94 }
95 errors.push(e);
96 }
97 }
98 }));
99 if (errors.length > 0) {
100 if (errors.length === 1) {
101 throw errors[0];
102 }
103 throw new utils_1.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
104 }
105 return finalResult;
106 }
107 loadSync(pointer, options) {
108 const resolvedPaths = this.resolveGlobsSync(pointer, options);
109 const finalResult = [];
110 const errors = [];
111 for (const path of resolvedPaths) {
112 if (this.canLoadSync(path, options)) {
113 try {
114 const normalizedFilePath = (0, path_1.isAbsolute)(path) ? path : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), path);
115 const rawSDL = (0, fs_1.readFileSync)(normalizedFilePath, { encoding: 'utf8' });
116 finalResult.push(this.handleFileContent(normalizedFilePath, rawSDL, options));
117 }
118 catch (e) {
119 if (process_1.env['DEBUG']) {
120 console.error(e);
121 }
122 errors.push(e);
123 }
124 }
125 }
126 if (errors.length > 0) {
127 if (errors.length === 1) {
128 throw errors[0];
129 }
130 throw new utils_1.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
131 }
132 return finalResult;
133 }
134 handleFileContent(normalizedFilePath, rawSDL, options) {
135 try {
136 return (0, utils_1.parseGraphQLJSON)(normalizedFilePath, rawSDL, options);
137 }
138 catch (e) {
139 throw new Error(`Unable to read JSON file: ${normalizedFilePath}: ${e.message || /* istanbul ignore next */ e}`);
140 }
141 }
142}
143exports.JsonFileLoader = JsonFileLoader;