-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.ts
More file actions
191 lines (181 loc) · 5.39 KB
/
Copy pathapi.ts
File metadata and controls
191 lines (181 loc) · 5.39 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
* 前端调用的后端 API 封装
* 所有 AI 请求走后端代理,不在前端暴露 DOUBAO_API_KEY
*
* - 开发:Vite 将 /api 代理到本地后端,使用相对路径 `/api` 即可。
* - 生产(推荐):Nginx 同域反代 `/api` → Node,构建时 **不要** 设置 VITE_API_BASE,仍用 `/api`。
* - 生产(API 独立子域等跨域):构建前在 `.env.production` 设置
* `VITE_API_BASE=https://api.你的域名.com/api`,并在服务端配置 `ALLOWED_ORIGINS`。
*/
export const API_BASE = (() => {
const raw = import.meta.env.VITE_API_BASE;
if (raw != null && String(raw).trim() !== '') {
return String(raw).replace(/\/$/, '');
}
return '/api';
})();
/** 登录后由前端设置:用于后端按 JWT 读取 Supabase user_profiles */
let supabaseAccessToken: string | null = null;
export function setSupabaseAccessToken(token: string | null) {
supabaseAccessToken = token;
}
async function request<T>(
path: string,
options: RequestInit & { json?: unknown } = {}
): Promise<T> {
const { json, headers, ...rest } = options;
const res = await fetch(`${API_BASE}${path}`, {
...rest,
headers: {
'Content-Type': 'application/json',
...(supabaseAccessToken ? { Authorization: `Bearer ${supabaseAccessToken}` } : {}),
...(headers || {}),
},
body: json !== undefined ? JSON.stringify(json) : rest.body,
});
if (!res.ok) {
const text = await res.text().catch(() => '');
try {
const parsed = text ? JSON.parse(text) : null;
const msg = parsed?.error || parsed?.message;
throw new Error(msg || `请求失败 ${res.status}`);
} catch {
throw new Error(text || `请求失败 ${res.status}`);
}
}
return res.json();
}
export interface ScanResult {
name?: string;
calories?: number;
protein?: number;
carbs?: number;
fat?: number;
/** 模型估算的当前份量重量(g),后端未命中时可能为 0 */
estimatedWeightGrams?: number;
/** 份量感知:small/medium/large 等 */
portionSize?: string;
/** 粗略食物类型:staple/meat/veg/soup 等 */
foodType?: string;
}
/** 食物图片识别 */
export async function aiScan(imageBase64: string, mimeType: string): Promise<ScanResult> {
return request<ScanResult>('/ai/scan', {
method: 'POST',
json: { imageBase64, mimeType },
});
}
/** 生成三餐方案(szu_south / szu_south_ai:均为 LLM 从候选 dishId 选菜并由数据库回填;none:通用 JSON 配餐) */
export async function aiPlan(
prompt: string,
selectedCanteen?: 'none' | 'szu_south' | 'szu_south_ai',
extra?: {
profile?: unknown;
targets?: { calories?: number };
avoidNames?: string[];
/** 仅更换某一餐时传入,并配合 fixedMeals(由前端从当前方案带上) */
refreshMealKey?: 'breakfast' | 'lunch' | 'dinner';
fixedMeals?: {
breakfast?: { name: string; calories: number; desc: string; category?: string; dishNames?: string[] };
lunch?: { name: string; calories: number; desc: string; category?: string; dishNames?: string[] };
dinner?: { name: string; calories: number; desc: string; category?: string; dishNames?: string[] };
};
}
): Promise<{
breakfast?: {
name: string;
calories: number;
desc: string;
category?: string;
dishNames?: string[];
dishIds?: string[];
protein?: number;
carbs?: number;
fat?: number;
source?: string;
};
lunch?: {
name: string;
calories: number;
desc: string;
category?: string;
dishNames?: string[];
dishIds?: string[];
protein?: number;
carbs?: number;
fat?: number;
source?: string;
};
dinner?: {
name: string;
calories: number;
desc: string;
category?: string;
dishNames?: string[];
dishIds?: string[];
protein?: number;
carbs?: number;
fat?: number;
source?: string;
};
}> {
return request('/ai/plan', {
method: 'POST',
json: {
prompt,
selectedCanteen: selectedCanteen ?? 'none',
profile: extra?.profile,
targets: extra?.targets,
avoidNames: extra?.avoidNames,
refreshMealKey: extra?.refreshMealKey,
fixedMeals: extra?.fixedMeals,
},
});
}
/** 获取食堂菜品列表(如深大南区菜单) */
export async function getCanteenDishes(canteen: string = 'szu_south'): Promise<{
dishes: Array<{
id?: string;
name: string;
calories: number;
protein: number;
carbs: number;
fat: number;
category: string;
description?: string;
}>;
}> {
return request(`/canteen/dishes?canteen=${encodeURIComponent(canteen)}`);
}
/** AI 对话(单轮) */
export async function aiChat(
message: string,
systemInstruction: string,
profile?: unknown
): Promise<{ text: string }> {
return request<{ text: string }>('/ai/chat', {
method: 'POST',
json: { message, systemInstruction, profile },
});
}
export interface HealthReportResponse {
aiOk?: boolean;
generatedAt?: string;
reportMarkdown?: string;
targets?: {
calories?: number;
protein?: number;
carbs?: number;
fat?: number;
waterMl?: number;
sleepHours?: number;
steps?: number;
};
}
/** 生成健康报告(基于用户档案 + 目标摄入) */
export async function aiHealthReport(profile: unknown, targets: unknown): Promise<HealthReportResponse> {
return request<HealthReportResponse>('/ai/report', {
method: 'POST',
json: { profile, targets },
});
}