advent22/ui/src/plugins/advent22.ts

96 lines
2.6 KiB
TypeScript

import axios, { AxiosInstance, ResponseType } from "axios";
import { App, Plugin } from "vue";
export class Advent22 {
private axios: AxiosInstance;
private api_auth = { username: "", password: "" };
public constructor() {
this.axios = axios.create({
timeout: 10000,
});
}
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) {
return this.api_baseurl;
}
while (endpoint.startsWith("/")) {
endpoint = endpoint.substring(1);
}
return `${this.api_baseurl}/${endpoint}`;
}
public set_api_auth(username: string, password: string) {
this.api_auth = { username: username, password: password };
}
private api_get<T>(endpoint: string): Promise<T>;
private api_get<T>(endpoint: string, responseType: ResponseType): Promise<T>;
private api_get<T>(
endpoint: string,
responseType: ResponseType = "json",
): Promise<T> {
const req_data = {
auth: this.api_auth,
responseType: responseType,
};
return new Promise<T>((resolve, reject) => {
this.axios
.get<T>(this.api_url(endpoint), req_data)
.then((response) => resolve(response.data))
.catch((reason) => {
console.error(`Failed to query ${endpoint}: ${reason}`);
reject([reason, endpoint]);
});
});
}
public api_get_blob(endpoint: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
this.api_get<Blob>(endpoint, "blob")
.then((data: Blob) => {
const reader = new FileReader();
reader.readAsDataURL(data);
reader.onloadend = () => {
if (typeof reader.result === "string") {
resolve(reader.result);
} else {
reject([endpoint, "failed data url"]);
}
};
})
.catch(reject);
});
}
public api_get_string(endpoint: string): Promise<string> {
return this.api_get<string>(endpoint);
}
public api_get_number(endpoint: string): Promise<number> {
return this.api_get<number>(endpoint);
}
}
export const Advent22Plugin: Plugin = {
install(app: App) {
app.config.globalProperties.$advent22 = new Advent22();
},
};