okami.mom/web-extract-go
git clone https://git.nkp.pet/okami.mom/web-extract-go
8af1784
main
1export class APIError extends Error { 2status :number 3constructor ( status :number , message :string ) { super ( message ); this . status = status } 4} 5 6export async function api < T > ( path :string , init :RequestInit = {}) :Promise < T > { 7const response = await fetch ( `/admin/api/ ${ path } ` , { 8 ...init , credentials :"same-origin" , 9headers :{ "Content-Type" :"application/json" , ...init . headers }, 10}) 11const data = await response . json () 12if ( response . status === 401 && path !== "login" && path !== "session" ) window . dispatchEvent ( new Event ( "session-expired" )) 13if ( ! response . ok ) throw new APIError ( response . status , data . error ?? "request failed" ) 14return 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 { 23try { const url = new URL ( value ); return / ^(https?:)$ / . test ( url . protocol ) ?url . href :undefined } catch { return undefined } 24}