-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathread-file-or-url.ts
More file actions
185 lines (177 loc) · 6.09 KB
/
read-file-or-url.ts
File metadata and controls
185 lines (177 loc) · 6.09 KB
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
import { parse, Source } from 'graphql';
import type { Schema } from 'js-yaml';
import { DEFAULT_SCHEMA, load as loadYamlFromJsYaml, Type } from 'js-yaml';
import { fs, path as pathModule } from '@graphql-mesh/cross-helpers';
import type { ImportFn, Logger, MeshFetch, MeshFetchRequestInit } from '@graphql-mesh/types';
import { isUrl, isValidPath, mapMaybePromise } from '@graphql-tools/utils';
import { fetch as defaultFetch } from '@whatwg-node/fetch';
import { loadFromModuleExportExpression } from './load-from-module-export-expression.js';
export interface ReadFileOrUrlOptions extends MeshFetchRequestInit {
allowUnknownExtensions?: boolean;
fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts' | 'graphql';
cwd: string;
fetch: MeshFetch;
importFn: ImportFn;
logger: Logger;
}
export { isUrl };
export async function readFileOrUrl<T>(
filePathOrUrl: string,
config: ReadFileOrUrlOptions,
): Promise<T> {
if (isUrl(filePathOrUrl)) {
config.logger.debug(`Fetching ${filePathOrUrl} via HTTP`);
return readUrl(filePathOrUrl, config);
} else if (
filePathOrUrl.startsWith('{') ||
filePathOrUrl.startsWith('[') ||
filePathOrUrl.startsWith('"')
) {
return JSON.parse(filePathOrUrl);
} else if (isValidPath(filePathOrUrl)) {
config.logger.debug(`Reading ${filePathOrUrl} from the file system`);
return readFile(filePathOrUrl, config);
} else {
return filePathOrUrl as T;
}
}
function getSchema(filepath: string, logger: Logger): Schema {
return DEFAULT_SCHEMA.extend([
new Type('!include', {
kind: 'scalar',
resolve(path: string) {
return typeof path === 'string';
},
construct(path: string) {
const newCwd = pathModule.dirname(filepath);
const absoluteFilePath = pathModule.isAbsolute(path)
? path
: pathModule.resolve(newCwd, path);
const content = fs.readFileSync(absoluteFilePath, 'utf8');
return loadYaml(absoluteFilePath, content, logger);
},
}),
new Type('!includes', {
kind: 'scalar',
resolve(path: string) {
return typeof path === 'string';
},
construct(path: string) {
const newCwd = pathModule.dirname(filepath);
const absoluteDirPath = pathModule.isAbsolute(path)
? path
: pathModule.resolve(newCwd, path);
const files = fs.readdirSync(absoluteDirPath);
return files.map(filePath => {
const absoluteFilePath = pathModule.resolve(absoluteDirPath, filePath);
const fileContent = fs.readFileSync(absoluteFilePath, 'utf8');
return loadYaml(absoluteFilePath, fileContent, logger);
});
},
}),
]);
}
export function loadYaml(filepath: string, content: string, logger: Logger): any {
return loadYamlFromJsYaml(content, {
filename: filepath,
schema: getSchema(filepath, logger),
onWarning(warning) {
logger.warn(`${filepath}: ${warning.message}\n${warning.stack}`);
},
});
}
function isAbsolute(path: string): boolean {
return path.startsWith('/') || /^[A-Z]:\\/i.test(path);
}
export function readFile<T>(
fileExpression: string,
{
allowUnknownExtensions,
cwd,
fallbackFormat,
importFn,
logger,
fetch = defaultFetch,
}: ReadFileOrUrlOptions,
): Promise<T> {
const [filePath] = fileExpression.split('#');
if (/js$/.test(filePath) || /ts$/.test(filePath) || /json$/.test(filePath)) {
return mapMaybePromise(
loadFromModuleExportExpression<T>(fileExpression, {
cwd,
importFn,
defaultExportName: 'default',
}),
res => JSON.parse(JSON.stringify(res)),
);
}
const actualPath = isAbsolute(filePath) ? filePath : `${cwd}/${filePath}`;
const url = `file://${actualPath}`;
return mapMaybePromise(fetch(url), res => {
if (/json$/.test(actualPath) || res.headers.get('content-type')?.includes('json')) {
return res.json();
}
return mapMaybePromise(res.text(), rawResult => {
if (/yaml$/.test(actualPath) || /yml$/.test(actualPath)) {
return loadYaml(actualPath, rawResult, logger);
} else if (
/graphql$/.test(actualPath) ||
/graphqls$/.test(actualPath) ||
/gql$/.test(actualPath) ||
/gqls$/.test(actualPath) ||
res.headers.get('content-type')?.includes('graphql')
) {
const source = new Source(rawResult, actualPath);
return parse(source);
} else if (fallbackFormat) {
switch (fallbackFormat) {
case 'json':
return JSON.parse(rawResult);
case 'yaml':
return loadYaml(actualPath, rawResult, logger);
case 'ts':
case 'js':
return importFn(actualPath);
case 'graphql':
return parse(new Source(rawResult, actualPath));
}
} else if (!allowUnknownExtensions) {
throw new Error(
`Failed to parse JSON/YAML. Ensure file '${filePath}' has ` +
`the correct extension (i.e. '.json', '.yaml', or '.yml).`,
);
}
return rawResult as unknown as T;
});
});
}
export async function readUrl<T>(path: string, config: ReadFileOrUrlOptions): Promise<T> {
const { allowUnknownExtensions, fallbackFormat } = config || {};
config.headers ||= {};
config.fetch ||= defaultFetch;
const response = await config.fetch(path, config);
const contentType = response.headers?.get('content-type') || '';
const responseText = await response.text();
config?.logger?.debug(`${path} returned `, responseText);
if (
/json$/.test(path) ||
contentType.startsWith('application/json') ||
fallbackFormat === 'json'
) {
return JSON.parse(responseText);
} else if (
/yaml$/.test(path) ||
/yml$/.test(path) ||
contentType.includes('yaml') ||
contentType.includes('yml') ||
fallbackFormat === 'yaml'
) {
return loadYaml(path, responseText, config?.logger);
} else if (!allowUnknownExtensions) {
throw new Error(
`Failed to parse JSON/YAML. Ensure URL '${path}' has ` +
`the correct extension (i.e. '.json', '.yaml', or '.yml) or mime type in the response headers.`,
);
}
return responseText as any;
}