Files

62 lines
2.8 KiB
JavaScript

// 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.
/** @typedef {import('../server/shapes.mjs').HttpError} HttpError */
/** One api() call: method + body + the keepalive flag + the domain-401 flag. */
/** @typedef {{ method?: string, body?: unknown, keepalive?: boolean, domain401?: boolean }} ApiOpts */
import { logEvent } from './log.mjs';
import { state } from './state.mjs';
import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
/** @returns {string} */
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
/** @param {string} t */
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 */ } };
/** @param {string} path @param {ApiOpts} [opts] @returns {Promise<any>} */
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 = /** @type {HttpError} */ (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}`);
// a 401 ends the session -- except the provider probe routes,
// where 401/403 is the endpoint's own auth refusal answering the
// add or the key check (the SPA's password branch, by design);
// those call sites opt out with domain401
if (res.status === 401 && path !== '/session' && authToken() && !opts.domain401) {
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;
}
}