-
Notifications
You must be signed in to change notification settings - Fork 760
Expand file tree
/
Copy pathexternal-value.js
More file actions
242 lines (217 loc) · 6.91 KB
/
external-value.js
File metadata and controls
242 lines (217 loc) · 6.91 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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import { fetch } from 'cross-fetch';
import createError from './create-error';
import lib from '.';
import url from 'url';
const externalValuesCache = {};
/**
* Resolves a path(optional absolute) and its base to an abolute URL.
* @api public
*/
function absoluteify(path, basePath) {
if (!ABSOLUTE_URL_REGEXP.test(path)) {
if (!basePath) {
throw new JSONRefError(
`Tried to resolve a relative URL, without having a basePath. path: '${path}' basePath: '${basePath}'`
);
}
return url.resolve(basePath, path);
}
return path;
}
/**
* Clears all external value caches.
* @param {String} url (optional) the original externalValue value of the cache item to be cleared.
* @api public
*/
function clearCache(url) {
if (typeof url !== 'undefined') {
delete externalValuesCache[url];
} else {
Object.keys(externalValuesCache).forEach((key) => {
delete externalValuesCache[key];
});
}
}
/**
* Fetches a document.
* @param {String} docPath the absolute URL of the document.
* @return {Promise} a promise of the document content.
* @api public
*/
const fetchRaw = (url) => fetch(url).then((res) => res.text);
const shouldResolveTestFn = [
// OAS 3.0 Response Media Type Examples externalValue
(path) =>
// ["paths", *, *, "responses", *, "content", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[3] === 'responses' &&
path[5] === 'content' &&
path[7] === 'examples' &&
path[9] === 'externalValue',
// OAS 3.0 Request Body Media Type Examples externalValue
(path) =>
// ["paths", *, *, "requestBody", "content", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[3] === 'requestBody' &&
path[4] === 'content' &&
path[6] === 'examples' &&
path[8] === 'externalValue',
// OAS 3.0 Parameter Examples externalValue
(path) =>
// ["paths", *, "parameters", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[2] === 'parameters' &&
path[4] === 'examples' &&
path[6] === 'externalValue',
(path) =>
// ["paths", *, *, "parameters", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[3] === 'parameters' &&
path[5] === 'examples' &&
path[7] === 'externalValue',
(path) =>
// ["paths", *, "parameters", *, "content", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[2] === 'parameters' &&
path[4] === 'content' &&
path[6] === 'examples' &&
path[8] === 'externalValue',
(path) =>
// ["paths", *, *, "parameters", *, "content", *, "examples", *, "externalValue"]
path[0] === 'paths' &&
path[3] === 'parameters' &&
path[5] === 'content' &&
path[7] === 'examples' &&
path[9] === 'externalValue',
];
const shouldSkipResolution = (path) => !shouldResolveTestFn.some((fn) => fn(path));
const ExternalValueError = createError('ExternalValueError', function cb(message, extra, oriError) {
this.originalError = oriError;
Object.assign(this, extra || {});
});
/**
* This plugin resolves externalValue keys.
* In order to do so it will use a cache in case the url was already requested.
* It will use the fetchRaw method in order get the raw content hosted on specified url.
* If successful retrieved it will replace the url with the actual value
*/
const plugin = {
key: 'externalValue',
plugin: (externalValue, _, fullPath, specmap, patch) => {
const parent = fullPath.slice(0, -1);
const parentObj = lib.getIn(patch.value, parent);
if (parentObj.value !== undefined) {
return undefined;
}
if (shouldSkipResolution(fullPath)) {
return undefined;
}
const { baseDoc } = specmap.getContext(fullPath);
if (typeof externalValue !== 'string') {
return new ExternalValueError('externalValue: must be a string', {
externalValue,
baseDoc,
fullPath,
});
}
const pathFragmentSplit = externalValue.split('#');
const externalValuePath = pathFragmentSplit[0];
let basePath;
try {
basePath = baseDoc || externalValuePath ? absoluteify(externalValuePath, baseDoc) : null;
} catch (e) {
return new ExternalValueError(
`Could not absoluteify externalValue: ${externalValue}`,
{
externalValue,
baseDoc,
fullPath,
}
);
}
try {
let externalValueOrPromise = getExternalValue(externalValue, fullPath);
if (typeof externalValueOrPromise === 'undefined') {
externalValueOrPromise = new ExternalValueError(
`Could not resolve externalValue: ${externalValue}`,
{
externalValue,
baseDoc,
fullPath,
}
);
}
// eslint-disable-next-line no-underscore-dangle
if (externalValueOrPromise.__value != null) {
// eslint-disable-next-line no-underscore-dangle
externalValueOrPromise = externalValueOrPromise.__value;
} else {
externalValueOrPromise = externalValueOrPromise.catch((e) => {
throw wrapError(e, {
externalValue,
fullPath,
});
});
}
if (externalValueOrPromise instanceof Error) {
return [lib.remove(fullPath), externalValueOrPromise];
}
const backupOriginalValuePatch = lib.add([...parent, '$externalValue'], externalValue);
const valuePatch = lib.replace([...parent, 'value'], externalValueOrPromise);
const cleanUpPatch = lib.remove(fullPath);
return [backupOriginalValuePatch, valuePatch, cleanUpPatch];
} catch (err) {
return [
lib.remove(fullPath),
wrapError(err, {
externalValue,
fullPath,
}),
];
}
},
};
const mod = Object.assign(plugin, {
wrapError,
clearCache,
ExternalValueError,
fetchRaw,
getExternalValue,
absoluteify
});
export default mod;
/**
* Wraps an error as ExternalValueError.
* @param {Error} e the error.
* @param {Object} extra (optional) optional data.
* @return {Error} an instance of ExternalValueError.
* @api public
*/
function wrapError(e, extra) {
let message;
if (e && e.response && e.response.body) {
message = `${e.response.body.code} ${e.response.body.message}`;
} else {
message = e.message;
}
return new ExternalValueError(`Could not resolve externalValue: ${message}`, extra, e);
}
/**
* Fetches and caches a ExternalValue.
* @param {String} docPath the absolute URL of the document.
* @return {Promise} a promise of the document content.
* @api public
*/
function getExternalValue(url) {
const val = externalValuesCache[url];
if (val) {
return lib.isPromise(val) ? val : Promise.resolve(val);
}
// NOTE: we need to use `mod.fetchRaw` in order to be able to overwrite it.
// Any tips on how to make this cleaner, please ping!
externalValuesCache[url] = mod.fetchRaw(url).then((raw) => {
externalValuesCache[url] = raw;
return raw;
});
return externalValuesCache[url];
}