ovdashboard/ui/src/plugins/ovdashboard.ts

100 lines
2.6 KiB
TypeScript
Raw Normal View History

2022-09-16 21:15:46 +00:00
import axios, { AxiosInstance } from 'axios';
2022-09-12 22:18:21 +00:00
import Vue from 'vue';
class OVDashboardPlugin {
2022-09-16 21:15:46 +00:00
private axios: AxiosInstance;
public constructor() {
// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const config = {
// baseURL: process.env.baseURL || process.env.apiUrl || ""
// timeout: 60 * 1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};
this.axios = axios.create(config);
}
2022-09-12 22:18:21 +00:00
public install(vue: typeof Vue) {
2022-09-16 21:15:46 +00:00
vue.prototype.$axios = this.axios;
2022-09-12 22:18:21 +00:00
vue.prototype.$ovdashboard = this;
}
private get api_baseurl(): string {
if (process.env.NODE_ENV === "production") {
return "//" + window.location.host + "/api/v1";
} else {
if (process.env.NODE_ENV !== "development") {
console.warn("Unexpected NODE_ENV value");
}
return "//" + window.location.hostname + ":8000/api/v1";
}
}
2022-09-12 22:22:40 +00:00
public api_url(endpoint?: string): string {
if (endpoint === undefined)
return this.api_baseurl;
else
return this.api_baseurl + "/" + endpoint;
}
2022-09-16 21:15:46 +00:00
public fail(name: string): (reason: unknown) => void {
return (reason: unknown) =>
console.warn("Failed to query", name, "-", reason);
}
public api_query_simple(
endpoint: string,
on_success: (data: unknown) => void
): void {
this.axios
.get(this.api_url(endpoint))
.then((response) => on_success(response.data))
.catch(this.fail(endpoint));
}
public api_query_simple_string(
endpoint: string,
on_success: (data: string) => void
): void {
this.api_query_simple(endpoint, (data) => {
if (typeof data !== "string") return;
on_success(data);
});
}
public api_query_simple_list(
endpoint: string,
on_success: (data: string[]) => void
): void {
this.api_query_simple(endpoint, (data) => {
if (!Array.isArray(data)) return;
if (!data.every((value) => typeof value === "string")) return;
on_success(data);
});
}
public api_query_simple_object(
endpoint: string,
on_success: (data: Record<string, unknown>) => void
): void {
this.api_query_simple(endpoint, (data) => {
if (typeof data !== "object") return;
if (data === null) return;
on_success(data as Record<string, unknown>);
});
}
}
export default new OVDashboardPlugin();