All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Settings → Data → Import gets "Restore a full backup" in place of the V1 import row. The zip from "Download backup" is uploaded and replaces the database, every setting and the uploaded files on the running server: - the staged database is upgraded to this schema (newer backups are refused), saved keys are re-encrypted for this server's key, interrupted jobs are marked, and the restoring session is carried over; - a pre-restore snapshot is written, running generations stop, and the file is swapped under the open DB handle (DB.replaceWith); uploads and media are copied into place and background work restarts. The /api/import/v1 endpoint stays for the V1 cutover (docs/MIGRATION.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
149 lines
5.9 KiB
TypeScript
149 lines
5.9 KiB
TypeScript
/** Thin client for the Study Desk API: JSON in, JSON out, typed errors, CSRF header on every call. */
|
|
|
|
export class ApiError extends Error {
|
|
status: number;
|
|
code: string;
|
|
details?: unknown;
|
|
constructor(status: number, code: string, message: string, details?: unknown) {
|
|
super(message);
|
|
this.name = 'ApiError';
|
|
this.status = status;
|
|
this.code = code;
|
|
this.details = details;
|
|
}
|
|
}
|
|
|
|
/** Set by the app shell: called when any request comes back 401 so the login screen can appear. */
|
|
let onUnauthorized: (() => void) | null = null;
|
|
export function setUnauthorizedHandler(fn: (() => void) | null): void {
|
|
onUnauthorized = fn;
|
|
}
|
|
|
|
const BASE_HEADERS = { 'X-Requested-With': 'studydesk' };
|
|
|
|
async function toError(res: Response): Promise<ApiError> {
|
|
let code = 'http_error';
|
|
let message = res.status >= 500 ? 'The server ran into a problem. Try again in a moment.' : `Request failed (${res.status})`;
|
|
let details: unknown;
|
|
try {
|
|
const body = await res.json();
|
|
if (body?.error) {
|
|
code = body.error.code ?? code;
|
|
message = body.error.message ?? message;
|
|
details = body.error.details;
|
|
}
|
|
} catch {
|
|
/* not JSON */
|
|
}
|
|
return new ApiError(res.status, code, message, details);
|
|
}
|
|
|
|
export async function request<T>(method: string, url: string, body?: unknown, init: { signal?: AbortSignal; publicCall?: boolean } = {}): Promise<T> {
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(url, {
|
|
method,
|
|
credentials: 'same-origin',
|
|
signal: init.signal,
|
|
headers: body instanceof FormData ? BASE_HEADERS : body !== undefined ? { ...BASE_HEADERS, 'Content-Type': 'application/json' } : BASE_HEADERS,
|
|
body: body instanceof FormData ? body : body !== undefined ? JSON.stringify(body) : undefined,
|
|
});
|
|
} catch (e) {
|
|
if ((e as Error)?.name === 'AbortError') throw e;
|
|
throw new ApiError(0, 'network', 'Could not reach the server. Check your connection and try again.');
|
|
}
|
|
if (!res.ok) {
|
|
const err = await toError(res);
|
|
if (res.status === 401 && !init.publicCall && err.code === 'unauthorized') onUnauthorized?.();
|
|
throw err;
|
|
}
|
|
if (res.status === 204) return undefined as T;
|
|
return (await res.json()) as T;
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal }),
|
|
post: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}),
|
|
put: <T>(url: string, body?: unknown) => request<T>('PUT', url, body ?? {}),
|
|
patch: <T>(url: string, body?: unknown) => request<T>('PATCH', url, body ?? {}),
|
|
del: <T>(url: string) => request<T>('DELETE', url),
|
|
upload: <T>(url: string, form: FormData) => request<T>('POST', url, form),
|
|
/** Public (share-link) calls never trigger the login screen. */
|
|
pub: <T>(url: string, signal?: AbortSignal) => request<T>('GET', url, undefined, { signal, publicCall: true }),
|
|
pubPost: <T>(url: string, body?: unknown) => request<T>('POST', url, body ?? {}, { publicCall: true }),
|
|
};
|
|
|
|
export function errorMessage(e: unknown, fallback = 'Something went wrong.'): string {
|
|
if (e instanceof ApiError) return e.message;
|
|
if (e instanceof Error && e.message) return e.message;
|
|
return fallback;
|
|
}
|
|
|
|
/** Uploads with progress (fetch cannot report upload progress). A Blob or File is sent as the raw body. */
|
|
export function uploadWithProgress<T>(url: string, form: FormData | Blob, onProgress: (fraction: number) => void): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('POST', url);
|
|
xhr.setRequestHeader('X-Requested-With', 'studydesk');
|
|
if (form instanceof Blob) xhr.setRequestHeader('Content-Type', form.type || 'application/octet-stream');
|
|
xhr.upload.onprogress = (e) => {
|
|
if (e.lengthComputable) onProgress(e.loaded / e.total);
|
|
};
|
|
xhr.onerror = () => reject(new ApiError(0, 'network', 'The upload was interrupted. Check your connection and try again.'));
|
|
xhr.onload = () => {
|
|
let body: any = null;
|
|
try {
|
|
body = JSON.parse(xhr.responseText);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
if (xhr.status >= 200 && xhr.status < 300) resolve(body as T);
|
|
else {
|
|
if (xhr.status === 401) onUnauthorized?.();
|
|
reject(new ApiError(xhr.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `Upload failed (${xhr.status})`, body?.error?.details));
|
|
}
|
|
};
|
|
xhr.send(form);
|
|
});
|
|
}
|
|
|
|
/** POSTs JSON (or GETs, when `body` is undefined) and reads a server-sent event stream of JSON objects. */
|
|
export async function streamEvents<T extends { type: string }>(url: string, body: unknown, onEvent: (event: T) => void, signal?: AbortSignal): Promise<void> {
|
|
const res = await fetch(url, {
|
|
method: body === undefined ? 'GET' : 'POST',
|
|
credentials: 'same-origin',
|
|
headers: body === undefined ? { ...BASE_HEADERS, Accept: 'text/event-stream' } : { ...BASE_HEADERS, 'Content-Type': 'application/json', Accept: 'text/event-stream' },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
signal,
|
|
});
|
|
if (!res.ok || !res.body) {
|
|
const err = await toError(res);
|
|
if (res.status === 401) onUnauthorized?.();
|
|
throw err;
|
|
}
|
|
const reader = res.body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let buffer = '';
|
|
for (;;) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
buffer += decoder.decode(value, { stream: true });
|
|
let idx: number;
|
|
while ((idx = buffer.search(/\r?\n\r?\n/)) >= 0) {
|
|
const block = buffer.slice(0, idx);
|
|
buffer = buffer.slice(idx).replace(/^\r?\n\r?\n/, '');
|
|
const data = block
|
|
.split(/\r?\n/)
|
|
.filter((l) => l.startsWith('data:'))
|
|
.map((l) => l.slice(5).trimStart())
|
|
.join('\n');
|
|
if (!data) continue;
|
|
try {
|
|
const event = JSON.parse(data) as T;
|
|
if (event.type !== 'ping') onEvent(event);
|
|
} catch {
|
|
/* skip malformed event */
|
|
}
|
|
}
|
|
}
|
|
}
|