advent22/ui/src/plugins/advent22.ts

110 lines
2.6 KiB
TypeScript
Raw Normal View History

2022-11-16 01:37:52 +00:00
import axios, { AxiosInstance, ResponseType } from 'axios';
2022-11-03 15:04:57 +00:00
import { App, Plugin } from 'vue';
export class Advent22 {
2022-11-16 01:37:52 +00:00
private axios: AxiosInstance;
private api_auth = { username: "", password: "" };
public constructor() {
this.axios = axios.create();
}
2022-11-03 15:04:57 +00:00
private get api_baseurl(): string {
// in production mode, return "//host/api"
if (process.env.NODE_ENV === "production") {
return `//${window.location.host}/api`;
} else if (process.env.NODE_ENV !== "development") {
// not in prouction or development mode
console.warn("Unexpected NODE_ENV value");
}
// in development mode, return "//hostname:8000/api"
return `//${window.location.hostname}:8000/api`;
}
public api_url(endpoint?: string): string {
if (endpoint === undefined)
2022-11-22 22:27:57 +00:00
return this.api_baseurl;
2022-11-03 15:04:57 +00:00
return `${this.api_baseurl}/${endpoint}`;
}
2022-11-16 01:37:52 +00:00
2022-12-14 02:39:32 +00:00
public set_api_auth(username: string, password: string) {
2022-11-16 01:37:52 +00:00
this.api_auth = { username: username, password: password };
}
private fail(name: string): (reason: unknown) => void {
return (reason: unknown) =>
console.warn("Failed to query", name, "-", reason);
}
private api_get<T>(
endpoint: string,
on_success: (data: T) => void,
responseType: ResponseType = "json",
): void {
const req_data = {
auth: this.api_auth,
responseType: responseType,
};
this.axios.get<T>(this.api_url(endpoint), req_data)
.then((response) => on_success(response.data))
.catch(this.fail(endpoint));
}
public api_get_blob(
endpoint: string,
on_success: (data: string) => void,
): void {
this.api_get<Blob>(
endpoint,
(data: Blob) => {
const reader = new FileReader();
reader.readAsDataURL(data);
reader.onloadend = () => {
if (typeof reader.result === "string")
on_success(reader.result);
2022-11-22 22:27:57 +00:00
else
this.fail(endpoint);
2022-11-16 01:37:52 +00:00
}
},
"blob",
);
}
2022-12-08 23:21:52 +00:00
public api_get_string(
endpoint: string,
on_success: (data: string) => void,
): void {
this.api_get<string>(
endpoint,
(data: string) => {
on_success(data);
}
);
}
2022-12-21 23:48:54 +00:00
public api_get_number(
endpoint: string,
on_success: (data: number) => void,
): void {
this.api_get<number>(
/**Explodiert Möglicherweise */
// oder auch nicht
endpoint,
(data: number) => {
on_success(data);
}
);
}
2022-11-03 15:04:57 +00:00
}
export const Advent22Plugin: Plugin = {
install(app: App) {
app.config.globalProperties.$advent22 = new Advent22();
}
}