Factorize fetch options

This commit is contained in:
Bastien Wirtz 2021-10-10 09:26:02 +02:00
parent a25e1b1a70
commit 0a3be103dc
5 changed files with 45 additions and 13 deletions

View File

@ -74,7 +74,8 @@
<Service
v-for="(item, index) in group.items"
:key="index"
v-bind:item="item"
:item="item"
:proxy="config.proxy"
:class="['column', `is-${12 / config.columns}`]"
/>
</template>
@ -102,7 +103,8 @@
<Service
v-for="(item, index) in group.items"
:key="index"
v-bind:item="item"
:item="item"
:proxy="config.proxy"
/>
</div>
</div>

View File

@ -42,3 +42,6 @@ colors:
message: ~
links: []
services: []
proxy: ~

View File

@ -1,5 +1,5 @@
<template>
<component v-bind:is="component" :item="item"></component>
<component v-bind:is="component" :item="item" :proxy="proxy"></component>
</template>
<script>
@ -9,6 +9,7 @@ export default {
name: "Service",
props: {
item: Object,
proxy: Object,
},
computed: {
component() {

View File

@ -20,10 +20,12 @@
</template>
<script>
import service from "@/mixins/service.js";
import Generic from "./Generic.vue";
export default {
name: "AdGuardHome",
mixins: [service],
props: {
item: Object,
},
@ -60,18 +62,14 @@ export default {
},
methods: {
fetchStatus: async function () {
this.status = await fetch(`${this.item.url}/control/status`, {
credentials: "include",
})
.then((response) => response.json())
.catch((e) => console.log(e));
this.status = await this.fetch("/control/status").catch((e) =>
console.log(e)
);
},
fetchStats: async function () {
this.stats = await fetch(`${this.item.url}/control/stats`, {
credentials: "include",
})
.then((response) => response.json())
.catch((e) => console.log(e));
this.stats = await this.fetch("/control/stats").catch((e) =>
console.log(e)
);
},
},
};

28
src/mixins/service.js Normal file
View File

@ -0,0 +1,28 @@
export default {
props: {
proxy: Object,
},
created: function () {
// custom service often consume info from an API using the item link (url) as a base url,
// but sometimes the base url is different. An optional alternative URL can be provided with the "endpoint" key.
this.endpoint = this.item.endpoint || this.item.url;
},
methods: {
fetch: function (path, init) {
let options = {};
if (this.proxy?.useCredentials) {
options.credentials = "include";
}
options = Object.assign(options, init);
return fetch(`${this.endpoint}/${path}`, options).then((response) => {
if (!response.ok) {
throw new Error("Not 2xx response");
}
return response.json();
});
},
},
};