Files
website/app/src/lib/api.js
2025-07-24 06:15:19 +03:00

60 lines
1.4 KiB
JavaScript

import { browser } from "$app/environment";
import { urljoin } from "$lib/util.js";
class API {
constructor() {
this.version = "v1";
}
// join given path and queries into an API URL
join(path = null, query = {}) {
let base = "";
if (browser) {
base = urljoin(import.meta.env.WEBSITE_API_PATH, this.version);
} else {
base = urljoin(import.meta.env.WEBSITE_API_URL, this.version);
}
return urljoin(base, path, query);
}
// check given JSON body for errors
check_err(json) {
if (!("error" in json))
throw new Error('API response is missing the "error" key');
if (json["error"] != "")
throw new Error(`API returned an error: ${json["error"]}`);
if (!("result" in json))
throw new Error('API response is missing the "result" key');
}
// make a HTTP GET request to the given URL
async GET(fetch, url) {
const res = await fetch(url);
const json = await res.json();
this.check_err(json);
return json["result"];
}
// get visitor metrics
async metrics(fetch) {
return await this.GET(fetch, this.join("/metrics"));
}
// get service list
async services(fetch) {
return await this.GET(fetch, this.join("/services"));
}
// get projects list
async projects(fetch) {
return await this.GET(fetch, this.join("/projects"));
}
}
const api = new API();
export default api;