okami.mom/web-extract-go

git clone https://git.nkp.pet/okami.mom/web-extract-go

nekomimi.petadmin: show what each request's decisions would cost on Jev8af1784

main
1.3 KiB24 linesraw
1export class APIError extends Error {
2  status: number
3  constructor(status: number, message: string) { super(message); this.status = status }
4}
5
6export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
7  const response = await fetch(`/admin/api/${path}`, {
8    ...init, credentials: "same-origin",
9    headers: { "Content-Type": "application/json", ...init.headers },
10  })
11  const data = await response.json()
12  if (response.status === 401 && path !== "login" && path !== "session") window.dispatchEvent(new Event("session-expired"))
13  if (!response.ok) throw new APIError(response.status, data.error ?? "request failed")
14  return data as T
15}
16
17export const message = (error: unknown) => error instanceof Error ? error.message : "something went wrong; try again"
18export const pretty = (value: unknown) => typeof value === "string" ? value : JSON.stringify(value, null, 2)
19export const number = (value: number) => new Intl.NumberFormat().format(value)
20export const usd = (value: number) => value < 0.01 ? `${(value * 100).toFixed(value < 0.001 ? 3 : 2)}¢` : `$${value.toFixed(2)}`
21export const time = (value: number) => new Date(value * 1000).toLocaleString()
22export function safeURL(value: string): string | undefined {
23  try { const url = new URL(value); return /^(https?:)$/.test(url.protocol) ? url.href : undefined } catch { return undefined }
24}