api.ts
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type {
Job,
ServerConfigView,
GenerateRequest,
GenerateResponse,
PreviewState,
LogEntry,
} from './types';
// 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。
const BASE = '';
async function http<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(BASE + path, {
...init,
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
});
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
throw new Error(data?.error || `请求失败 (${res.status})`);
}
return data as T;
}
export const api = {
getConfig: () => http<ServerConfigView>('/api/config'),
generate: (req: GenerateRequest) =>
http<GenerateResponse>('/api/generate', {
method: 'POST',
body: JSON.stringify(req),
}),
listJobs: () => http<{ jobs: Job[] }>('/api/jobs'),
getJob: (id: string) => http<Job>(`/api/job/${id}`),
getPreview: () => http<PreviewState>('/api/preview'),
startPreview: (appPath?: string) =>
http<{ ok: boolean; error?: string }>('/api/preview', {
method: 'POST',
body: JSON.stringify({ appPath }),
}),
stopPreview: () =>
http<{ ok: boolean }>('/api/preview/stop', { method: 'POST' }),
};
export type SSEEventName = 'log' | 'jobs' | 'preview' | string;
export interface SSEPayload {
event: SSEEventName;
data: unknown;
}
/**
* 订阅后端 SSE 流(/api/stream)。后端会推送三种事件:
* - log: 实时引擎日志 (LogEntry)
* - jobs: 任务列表快照 (Job[]),每次状态变更都会重发
* - preview: 预览服务状态 (PreviewState)
* 返回取消订阅函数。
*/
export function subscribeSSE(
onMessage: (msg: SSEPayload) => void,
onError?: (e: Event) => void,
): () => void {
const es = new EventSource('/api/stream');
const handle = (name: SSEEventName) => (e: MessageEvent) => {
try {
onMessage({ event: name, data: JSON.parse(e.data) });
} catch {
/* ignore malformed */
}
};
es.addEventListener('log', handle('log') as EventListener);
es.addEventListener('jobs', handle('jobs') as EventListener);
es.addEventListener('preview', handle('preview') as EventListener);
es.onerror = (e) => {
onError?.(e);
};
return () => es.close();
}
export type { LogEntry, Job };