63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import { createAlova } from "alova";
|
|
import adapterFetch from "alova/fetch";
|
|
|
|
export type UploadedFile = {
|
|
originalName: string;
|
|
fileName: string;
|
|
url: string;
|
|
size: number;
|
|
contentType: string | null;
|
|
};
|
|
|
|
export type RecognitionRequest = {
|
|
url: string;
|
|
type: string;
|
|
};
|
|
|
|
export type RecognitionResponse = {
|
|
url: string;
|
|
type: string;
|
|
ppStructureResult: unknown;
|
|
};
|
|
|
|
const defaultApiBaseUrl = "http://192.168.1.137:8082";
|
|
|
|
function normalizeBaseUrl(baseUrl: string | undefined) {
|
|
const value = baseUrl?.trim() || defaultApiBaseUrl;
|
|
return value.endsWith("/") ? value.slice(0, -1) : value;
|
|
}
|
|
|
|
async function readErrorMessage(response: Response) {
|
|
const fallback = `请求失败,状态码 ${response.status}`;
|
|
|
|
try {
|
|
const data = await response.json();
|
|
return data.detail || data.message || data.error || fallback;
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
const http = createAlova({
|
|
baseURL: normalizeBaseUrl(import.meta.env.VITE_API_BASE_URL),
|
|
requestAdapter: adapterFetch(),
|
|
responded: async (response) => {
|
|
if (!response.ok) {
|
|
throw new Error(await readErrorMessage(response));
|
|
}
|
|
|
|
return response.json();
|
|
},
|
|
});
|
|
|
|
export function uploadFile(file: File) {
|
|
const formData = new FormData();
|
|
formData.append("file", file);
|
|
|
|
return http.Post<UploadedFile>("/api/files/upload", formData).send();
|
|
}
|
|
|
|
export function recognizeDocument(data: RecognitionRequest) {
|
|
return http.Post<RecognitionResponse>("/api/recognitions/start", data).send();
|
|
}
|