Files
road-compiler/workbench/client/src/lib/api.ts
T

89 lines
3.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { WorkbenchState } from '../types/state';
import type {
EditPreviewRequest,
EditPreviewResponse,
EditSelection,
EditStateResponse,
SaveEditsRequest,
SaveEditsResponse,
} from '../edit/types';
/** Carries the status and parsed body so callers can branch on 409 rather than on message text. */
export class ApiError extends Error {
constructor(
message: string,
readonly status: number,
readonly body: unknown,
) {
super(message);
this.name = 'ApiError';
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(path, { cache: 'no-store', ...init });
// Read as text first. A dead backend behind the dev proxy answers with an empty
// body, and `response.json()` then throws "Unexpected end of JSON input" —
// which says nothing about the actual problem.
const text = await response.text();
if (!text) throw new ApiError(`${path} 返回空响应(HTTP ${response.status}),后端可能未启动`, response.status, null);
let value: T & { ok?: boolean; error?: string };
try {
value = JSON.parse(text) as T & { ok?: boolean; error?: string };
} catch {
throw new ApiError(`${path} 返回了非 JSON 响应(HTTP ${response.status})`, response.status, text);
}
if (!response.ok || value.ok === false)
throw new ApiError(value.error || `HTTP ${response.status}`, response.status, value);
return value;
}
const json = (body: unknown, signal?: AbortSignal): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
...(signal ? { signal } : {}),
});
/** A save lost the single-writer race; `body.current.documentVersion` holds the server's version. */
export function isVersionConflict(error: unknown): error is ApiError {
return error instanceof ApiError && error.status === 409;
}
export const api = {
state: () => request<WorkbenchState | { active: false }>('/api/state'),
import: (file: File) => {
const body = new FormData();
body.append('file', file, file.name);
return request<WorkbenchState>('/api/import', { method: 'POST', body });
},
overrides: (overrides: unknown[]) =>
request<{ overrides: WorkbenchState['overrides'] }>(
'/api/overrides',
json({ schema: 'native-road-overrides/v1', overrides }),
),
compile: () => request<WorkbenchState>('/api/compile', { method: 'POST' }),
signals: (document: unknown) =>
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals', json(document)),
generateSignals: () =>
request<Pick<WorkbenchState, 'trafficSignals' | 'trafficRuntime'>>('/api/traffic-signals/generate', {
method: 'POST',
}),
acceptJunctionCandidate: (index: number) =>
request<WorkbenchState & { added: { id: string } }>('/api/junction-clusters', json({ index })),
// Direct-edit endpoints used by the in-page browser/edit switch.
editState: (selection?: EditSelection) => {
const query = selection ? `?${new URLSearchParams(selection as Record<string, string>)}` : '';
return request<EditStateResponse | { active: false }>(`/api/edit-state${query}`);
},
/**
* `signal` comes from the caller's AbortController: the request layer only
* sends and cancels, while `EditSession` decides which responses to keep.
*/
editPreview: (body: EditPreviewRequest, signal?: AbortSignal) =>
request<EditPreviewResponse>('/api/edit-preview', json(body, signal)),
/** Throws an `ApiError` with status 409 when another writer moved the version. */
saveEdits: (body: SaveEditsRequest) => request<SaveEditsResponse>('/api/edits', json(body)),
};