Files
radicle-explorer/src/api.ts
T
Alexis Sellier e6f4441be7 Revise seed config
No longer use `Config` to store the seed config.

Signed-off-by: Alexis Sellier <self@cloudhead.io>
2022-02-09 13:27:12 +01:00

62 lines
1.3 KiB
TypeScript

export interface Host {
host: string;
port: number;
}
export async function get(
path: string,
params: Record<string, any>,
api: Host
): Promise<any> {
const query: Record<string, string> = {};
for (const [key, val] of Object.entries(params)) {
query[key] = val.toString();
}
const base = api.host;
const port = api.port;
const search = new URLSearchParams(query).toString();
// Allow using the functionality with local runned http-api
const isLocalhost = /^0.0.0.0$/.test(base);
const protocol = isLocalhost ? "http://" : "https://";
path = path.startsWith("/") ? path.slice(1) : path;
const baseUrl = path
? `${protocol}${base}:${port}/v1/${path}`
: `${protocol}${base}:${port}`;
const url = search ? `${baseUrl}?${search}` : baseUrl;
let response = null;
try {
response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
} catch (err) {
throw new ApiError(url, "API request failed");
}
if (! response.ok) {
throw new ApiError(url, "Not found");
}
return response.json();
}
class ApiError extends Error {
url: string;
constructor(url: string, message: string) {
super(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ApiError);
}
this.name = "ApiError";
this.url = url;
}
}