import { ApiError } from "./apiError.js";
import { u } from "./base.js";
async function readBody(res) {
try {
return await res.text();
} catch (_) {
return "";
}
}
export async function apiGet(path) {
const url = u(path);
let res;
try {
res = await fetch(url, { headers: { Accept: "application/json" } });
} catch (e) {
throw new ApiError("GET", url, null, e.message);
}
if (!res.ok)
throw new ApiError(
"GET",
url,
res.status,
res.statusText,
await readBody(res),
);
return res.json();
}
export async function apiPutJSON(path, body) {
return fetch(u(path), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
export async function apiPost(path, body) {
const opts = body
? {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
: { method: "POST" };
return fetch(u(path), opts);
}
export async function apiSend(path, opts = {}) {
const merged = {
...opts,
headers: { "Content-Type": "application/json", ...(opts.headers || {}) },
};
const method = opts.method || "GET";
const url = u(path);
let res;
try {
res = await fetch(url, merged);
} catch (e) {
throw new ApiError(method, url, null, e.message);
}
if (!res.ok)
throw new ApiError(
method,
url,
res.status,
res.statusText,
await readBody(res),
);
const text = await res.text();
return text ? JSON.parse(text) : null;
}
export async function localGet(path) {
const url = u(path);
let res;
try {
res = await fetch(url, {
headers: { Accept: "application/json" },
credentials: "same-origin",
});
} catch (e) {
throw new ApiError("GET", url, null, e.message);
}
if (!res.ok)
throw new ApiError(
"GET",
url,
res.status,
res.statusText,
await readBody(res),
);
return res.json();
}
export async function localFetch(path, opts = {}) {
return fetch(u(path), { credentials: "same-origin", ...opts });
}