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