advent22/ui/src/lib/api.ts

86 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-08-23 16:38:04 +00:00
import axios, {
AxiosBasicCredentials,
type AxiosRequestConfig,
type Method,
type RawAxiosRequestHeaders,
} from "axios";
import { APIError } from "./api_error";
2023-09-12 16:39:18 +00:00
2024-08-23 16:38:04 +00:00
interface Params {
endpoint: string;
method?: Method;
data?: unknown;
headers?: RawAxiosRequestHeaders;
config?: AxiosRequestConfig;
2023-11-03 14:40:44 +00:00
}
2024-08-23 16:38:04 +00:00
export class API {
private static get api_baseurl(): string {
// in production mode, return "proto://hostname/api"
if (process.env.NODE_ENV === "production") {
return `${window.location.protocol}//${window.location.host}/api`;
} else if (process.env.NODE_ENV !== "development") {
// not in prouction or development mode
console.warn("Unexpected NODE_ENV value");
}
2023-09-12 16:55:34 +00:00
2024-08-23 16:38:04 +00:00
// in development mode, return "proto://hostname:8000/api"
return `${window.location.protocol}//${window.location.hostname}:8000/api`;
}
private static readonly axios = axios.create({
timeout: 10e3,
baseURL: this.api_baseurl,
});
private static readonly creds_key = "advent22/credentials";
2024-08-23 16:38:04 +00:00
public static set creds(value: AxiosBasicCredentials | null) {
if (value === null) {
localStorage.removeItem(this.creds_key);
} else {
localStorage.setItem(this.creds_key, JSON.stringify(value));
2024-08-23 16:38:04 +00:00
}
}
public static get creds(): AxiosBasicCredentials {
const auth_json = localStorage.getItem(this.creds_key);
if (auth_json !== null) {
return JSON.parse(auth_json);
} else {
return { username: "", password: "" };
}
2024-08-23 16:38:04 +00:00
}
private static get_axios_config({
endpoint,
method = "GET",
data,
headers = {},
config = {},
}: Params): AxiosRequestConfig {
return {
url: endpoint,
method: method,
data: data,
auth: this.creds,
headers: headers,
...config,
};
}
2023-09-12 16:55:34 +00:00
2024-08-23 16:38:04 +00:00
public static async request<T = string>(p: Params): Promise<T>;
public static async request<T = string>(p: string): Promise<T>;
public static async request<T = string>(p: Params | string): Promise<T> {
if (typeof p === "string") p = { endpoint: p };
2023-09-21 12:25:23 +00:00
2024-08-23 16:38:04 +00:00
try {
const response = await this.axios.request<T>(this.get_axios_config(p));
return response.data;
} catch (reason) {
console.error(`Failed to query ${p.endpoint}: ${reason}`);
throw new APIError(reason, p.endpoint);
2023-09-21 09:53:30 +00:00
}
}
}