]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/mixins/service.js
Changed config and header names as per @bastienwirtz feedback
[github/bastienwirtz/homer.git] / src / mixins / service.js
1 const merge = require("lodash.merge");
2
3 export default {
4 props: {
5 proxy: Object,
6 forwarder: Object,
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;
12
13 if (this.endpoint.endsWith("/")) {
14 this.endpoint = this.endpoint.slice(0, -1);
15 }
16 },
17 methods: {
18 fetch: function (path, init, json = true) {
19 let options = {};
20
21 if (this.proxy?.useCredentials) {
22 options.credentials = "include";
23 }
24
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
31 if (this.forwarder?.apikey) {
32 options.headers = {
33 "X-Homer-Forwarder-Api-Key": this.forwarder.apikey,
34 };
35 }
36
37 if (path.startsWith("/")) {
38 path = path.slice(1);
39 }
40
41 let url = path ? `${this.endpoint}/${path}` : this.endpoint;
42
43 if (this.forwarder?.url) {
44 options.headers = {
45 ...(options.headers || {}),
46 "X-Homer-Forwarder-Url": url,
47 };
48 url = this.forwarder.url;
49 }
50
51 options = merge(options, init);
52
53 return fetch(url, options).then((response) => {
54 if (!response.ok) {
55 throw new Error("Not 2xx response");
56 }
57
58 return json ? response.json() : response;
59 });
60 },
61 },
62 };