]>
Commit | Line | Data |
---|---|---|
a2dfffab ES |
1 | const merge = require("lodash.merge"); |
2 | ||
0a3be103 BW |
3 | export default { |
4 | props: { | |
5 | proxy: Object, | |
240e3f0e | 6 | forwarder: Object, |
0a3be103 BW |
7 | }, |
8 | created: function () { | |
9 | // custom service often consume info from an API using the item link (url) as a base url, | |
10 | // but sometimes the base url is different. An optional alternative URL can be provided with the "endpoint" key. | |
11 | this.endpoint = this.item.endpoint || this.item.url; | |
efc2bbb8 BW |
12 | |
13 | if (this.endpoint.endsWith("/")) { | |
14 | this.endpoint = this.endpoint.slice(0, -1); | |
15 | } | |
0a3be103 BW |
16 | }, |
17 | methods: { | |
2fba0435 | 18 | fetch: function (path, init, json = true) { |
0a3be103 BW |
19 | let options = {}; |
20 | ||
21 | if (this.proxy?.useCredentials) { | |
22 | options.credentials = "include"; | |
23 | } | |
24 | ||
efc2bbb8 BW |
25 | // Each item can override the credential settings |
26 | if (this.item.useCredentials !== undefined) { | |
27 | options.credentials = | |
28 | this.item.useCredentials === true ? "include" : "omit"; | |
29 | } | |
30 | ||
240e3f0e | 31 | if (this.forwarder?.apikey) { |
a2dfffab | 32 | options.headers = { |
240e3f0e | 33 | "X-Homer-Forwarder-Api-Key": this.forwarder.apikey, |
a2dfffab ES |
34 | }; |
35 | } | |
0a3be103 | 36 | |
efc2bbb8 BW |
37 | if (path.startsWith("/")) { |
38 | path = path.slice(1); | |
39 | } | |
40 | ||
a2dfffab | 41 | let url = path ? `${this.endpoint}/${path}` : this.endpoint; |
1340a8e6 | 42 | |
240e3f0e | 43 | if (this.forwarder?.url) { |
a2dfffab ES |
44 | options.headers = { |
45 | ...(options.headers || {}), | |
240e3f0e | 46 | "X-Homer-Forwarder-Url": url, |
a2dfffab | 47 | }; |
240e3f0e | 48 | url = this.forwarder.url; |
1340a8e6 JW |
49 | } |
50 | ||
a2dfffab ES |
51 | options = merge(options, init); |
52 | ||
1340a8e6 | 53 | return fetch(url, options).then((response) => { |
0a3be103 BW |
54 | if (!response.ok) { |
55 | throw new Error("Not 2xx response"); | |
56 | } | |
2fba0435 BW |
57 | |
58 | return json ? response.json() : response; | |
0a3be103 BW |
59 | }); |
60 | }, | |
61 | }, | |
62 | }; |