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(); } 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 fail(name: string, reason: unknown): void { console.warn("Failed to query", name, "-", reason); } private api_get( endpoint: string, on_success: (data: T) => void, on_failure: (name: string, reason: unknown) => void, responseType: ResponseType = "json", ) { const req_data = { auth: this.api_auth, responseType: responseType, }; this.axios .get(this.api_url(endpoint), req_data) .then((response) => on_success(response.data)) .catch((reason) => on_failure(endpoint, reason)); } public api_get_blob( endpoint: string, on_success: (data: string) => void, on_failure: (name: string, reason: unknown) => void = this.fail, ) { this.api_get( endpoint, (data: Blob) => { const reader = new FileReader(); reader.readAsDataURL(data); reader.onloadend = () => { if (typeof reader.result === "string") { on_success(reader.result); } else { on_failure(endpoint, "failed data url"); } }; }, on_failure, "blob", ); } public api_get_string( endpoint: string, on_success: (data: string) => void, on_failure: (name: string, reason: unknown) => void = this.fail, ) { this.api_get( endpoint, (data: string) => { on_success(data); }, on_failure, ); } public api_get_number( endpoint: string, on_success: (data: number) => void, on_failure: (name: string, reason: unknown) => void = this.fail, ) { this.api_get( endpoint, (data: number) => { on_success(data); }, on_failure, ); } } export const Advent22Plugin: Plugin = { install(app: App) { app.config.globalProperties.$advent22 = new Advent22(); }, };