84 lines
2.8 KiB
TypeScript
84 lines
2.8 KiB
TypeScript
import type { ApiProjectRow, ProjectDocument } from '../types/project';
|
|
|
|
// ── Base URL ──────────────────────────────────────────────────────────────────
|
|
// CRA proxy forwards /api/* to backend:4000 in Docker; in local dev the
|
|
// package.json proxy field handles it. We always use a relative path.
|
|
|
|
const BASE = '/api/projects';
|
|
|
|
// ── Response helpers ──────────────────────────────────────────────────────────
|
|
|
|
async function handleResponse<T>(res: Response): Promise<T> {
|
|
if (!res.ok) {
|
|
let message = `HTTP ${res.status}`;
|
|
try {
|
|
const body = await res.json() as { error?: string };
|
|
if (body.error) message = body.error;
|
|
} catch {
|
|
// ignore parse failure — use status text
|
|
message = res.statusText || message;
|
|
}
|
|
throw new Error(message);
|
|
}
|
|
return res.json() as Promise<T>;
|
|
}
|
|
|
|
// ── API functions ─────────────────────────────────────────────────────────────
|
|
|
|
/** List all projects (summary rows — project_json is included but may be large). */
|
|
export async function listProjects(): Promise<ApiProjectRow[]> {
|
|
const res = await fetch(BASE);
|
|
return handleResponse<ApiProjectRow[]>(res);
|
|
}
|
|
|
|
/** Fetch a single project by numeric ID. */
|
|
export async function getProject(id: number): Promise<ApiProjectRow> {
|
|
const res = await fetch(`${BASE}/${id}`);
|
|
return handleResponse<ApiProjectRow>(res);
|
|
}
|
|
|
|
/**
|
|
* Create a new project.
|
|
* Sends the canonical project JSON as the `project_json` field.
|
|
* The backend stores `name` and `description` as top-level columns for
|
|
* listing/search, and the full JSON as `project_json`.
|
|
*/
|
|
export async function createProject(
|
|
name: string,
|
|
description: string,
|
|
doc: ProjectDocument,
|
|
): Promise<ApiProjectRow> {
|
|
const res = await fetch(BASE, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
name,
|
|
description,
|
|
project_json: JSON.stringify(doc),
|
|
}),
|
|
});
|
|
return handleResponse<ApiProjectRow>(res);
|
|
}
|
|
|
|
/**
|
|
* Save (update) an existing project.
|
|
* Always sends the full canonical project JSON so the backend stays in sync.
|
|
*/
|
|
export async function saveProject(
|
|
id: number,
|
|
name: string,
|
|
description: string,
|
|
doc: ProjectDocument,
|
|
): Promise<ApiProjectRow> {
|
|
const res = await fetch(`${BASE}/${id}`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
name,
|
|
description,
|
|
project_json: JSON.stringify(doc),
|
|
}),
|
|
});
|
|
return handleResponse<ApiProjectRow>(res);
|
|
}
|