Files
tiny-worlds/web/client.mjs
T

51 lines
2.1 KiB
JavaScript
Raw Normal View History

// web/client.mjs -- the REST client: the one fetch choke point.
//
// Every call is logged to the diagnostics (status + duration); a
// rejected token ends the session -- drop it and show the claim view;
// every path leads there until a fresh one is claimed.
import { logEvent } from './log.mjs';
import { state } from './state.mjs';
import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked -- the session just won't persist */ } };
export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
export async function api(path, opts = {}) {
const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`;
try {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: {
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page -- the notepad flush
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const e = new Error(data.error ?? `${res.status}`);
e.detail = data.detail;
e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms -- ${e.message}`);
if (res.status === 401 && path !== '/session' && authToken()) {
clearToken();
state.me = null;
logEvent('nav', 'signed out: token rejected');
setTimeout(render, 0);
}
throw e;
}
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
return data;
} catch (e) {
if (!e.status) logEvent('api', `${label} FAILED ${Math.round(performance.now() - started)}ms -- ${e.message}`); // network level
throw e;
}
}