-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathURLResolver.js
63 lines (59 loc) · 2.22 KB
/
URLResolver.js
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
/* eslint-disable import/extensions */
import Resolver from './Resolver.js';
import SelectiveResolver from './SelectiveResolver.js';
import PrefixSelector from './PrefixSelector.js';
export default class URLResolver extends SelectiveResolver {
constructor(selector, fetchArg) {
super(selector || (new PrefixSelector('url.')));
this.$fetch = fetchArg;
}
resolve(config) {
const self = this;
const resolvedConfig = Resolver.prototype.mapValuesDeep(config, (v) => {
if (self.selector.matches(v)) {
try {
return v;
} catch (e) {
return v;
}
}
return v;
});
return resolvedConfig;
}
async asyncResolve(config, parentConfig, path) {
const self = this;
const resolvedConfig = await Resolver.prototype.asyncMapValuesDeep(config, async (v) => {
if (self.selector.matches(v)) {
try {
const selectedValue = self.selector.resolveValue(v);
const urlPath = path.substring(0, path.lastIndexOf('.'));
const method = parentConfig.has(`${urlPath}.method`) ? parentConfig.get(`${urlPath}.method`) : null;
const authorization = parentConfig.has(`${urlPath}.authorization`) ? parentConfig.get(`${urlPath}.authorization`) : null;
const body = parentConfig.has(`${urlPath}.body`) ? parentConfig.get(`${urlPath}.body`) : null;
const headers = parentConfig.has(`${urlPath}.headers`) ? parentConfig.get(`${urlPath}.headers`) : null;
const fetchedValue = await this.fetch(
selectedValue, authorization, method, body, headers,
);
return fetchedValue;
} catch (e) {
return v;
}
}
return v;
});
return resolvedConfig;
}
async fetch(url, authorization, method, body, headers) {
if (!this.$fetch) {
throw new Error('fetch is required');
}
const $headers = authorization ? { authorization } : {};
Object.assign($headers, headers);
const opts = { method: method || 'get', headers: $headers };
if (method && method?.toLowerCase() !== 'get' && method?.toLowerCase() !== 'head') {
Object.assign(opts, JSON.stringify(body || {}));
}
return this.$fetch(url, opts).then((res) => res.json());
}
}