Files
offerpai_browser_plug/src/lib/api.ts
T
2026-05-09 10:12:21 +08:00

71 lines
2.0 KiB
TypeScript

/**
* 后端 API 通信模块
* 封装了与 Java 后端和 Python AI 后端的 REST API 请求方法
* 注意:项目有两个后端,新增接口时务必确认是哪个后端的
*/
/** Java 后端基础地址 */
const BASE_URL = "http://localhost:8080/api"
/** Python AI 后端基础地址 */
const AI_BASE_URL = "http://localhost:5000/api"
/** 请求配置选项 */
interface ApiOptions {
/** 请求方法,默认 GET */
method?: string
/** 请求体数据 */
body?: unknown
/** 自定义请求头 */
headers?: Record<string, string>
}
/**
* 通用请求方法
* @param baseUrl - 后端基础地址
* @param path - 接口路径,如 /user/info
* @param options - 请求配置
* @returns 解析后的 JSON 响应数据
* @throws 当响应状态码非 2xx 时抛出错误
*/
async function request<T>(baseUrl: string, path: string, options: ApiOptions = {}): Promise<T> {
const { method = "GET", body, headers = {} } = options
const res = await fetch(`${baseUrl}${path}`, {
method,
headers: {
"Content-Type": "application/json",
...headers
},
body: body ? JSON.stringify(body) : undefined
})
if (!res.ok) {
throw new Error(`API Error: ${res.status} ${res.statusText}`)
}
return res.json()
}
/**
* Java 后端接口
* 用于用户管理、简历数据、投递记录等业务接口
*/
export const javaApi = {
/** 发送 GET 请求到 Java 后端 */
get: <T>(path: string) => request<T>(BASE_URL, path),
/** 发送 POST 请求到 Java 后端 */
post: <T>(path: string, body: unknown) => request<T>(BASE_URL, path, { method: "POST", body })
}
/**
* Python AI 后端接口
* 用于页面结构分析、智能填表、简历优化等 AI 功能接口
*/
export const aiApi = {
/** 发送 GET 请求到 Python AI 后端 */
get: <T>(path: string) => request<T>(AI_BASE_URL, path),
/** 发送 POST 请求到 Python AI 后端 */
post: <T>(path: string, body: unknown) => request<T>(AI_BASE_URL, path, { method: "POST", body })
}