43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import { API } from "./site";
|
|
|
|
export function getBearerToken(request: Request): string | null {
|
|
const auth = request.headers.get("authorization");
|
|
if (auth?.startsWith("Bearer ")) return auth.slice(7);
|
|
return null;
|
|
}
|
|
|
|
export async function meshkeeFetch(
|
|
path: string,
|
|
init?: RequestInit & { token?: string | null },
|
|
): Promise<{ ok: boolean; status: number; data: unknown }> {
|
|
const headers = new Headers(init?.headers);
|
|
if (!headers.has("Content-Type") && init?.body) {
|
|
headers.set("Content-Type", "application/json");
|
|
}
|
|
if (init?.token) {
|
|
headers.set("Authorization", `Bearer ${init.token}`);
|
|
}
|
|
|
|
const res = await fetch(`${API.base}${path}`, {
|
|
...init,
|
|
headers,
|
|
});
|
|
|
|
let data: unknown = null;
|
|
try {
|
|
data = await res.json();
|
|
} catch {
|
|
data = null;
|
|
}
|
|
|
|
return { ok: res.ok, status: res.status, data };
|
|
}
|
|
|
|
export function jsonResponse(data: unknown, status = 200) {
|
|
return Response.json(data, { status });
|
|
}
|
|
|
|
export function unauthorizedResponse() {
|
|
return jsonResponse({ error: "Unauthorized" }, 401);
|
|
}
|