You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.5 KiB
87 lines
2.5 KiB
import { a as useAuthStore, b as useRouter } from './server.mjs';
|
|
import { u as useLoading } from './useLoading-D4zrSa2m.mjs';
|
|
|
|
async function request(url, body, extraHeaders) {
|
|
const auth = useAuthStore();
|
|
const router = useRouter();
|
|
const headers = {
|
|
"Content-Type": "application/json"
|
|
};
|
|
if (auth.token) {
|
|
headers["Authorization"] = auth.token;
|
|
}
|
|
if (extraHeaders) {
|
|
Object.assign(headers, extraHeaders);
|
|
}
|
|
const response = await fetch(url, {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(body)
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error: ${response.status}`);
|
|
}
|
|
const result = await response.json();
|
|
if (result.code === 18) {
|
|
auth.logout();
|
|
router.push("/");
|
|
throw new Error(result.msg || "Unauthorized");
|
|
}
|
|
if (result.code !== 0) {
|
|
throw new Error(result.msg || "Unknown error");
|
|
}
|
|
return result.data;
|
|
}
|
|
const READONLY_RE = /^(get|list|load|query|fetch|search|count|stat|export|check)/i;
|
|
function isMutating(method) {
|
|
return !READONLY_RE.test(method);
|
|
}
|
|
function useApi() {
|
|
const auth = useAuthStore();
|
|
const { begin, end } = useLoading();
|
|
async function webApi(method, data) {
|
|
const extraHeaders = {};
|
|
if (auth.currentAppId) {
|
|
extraHeaders["X-App-Id"] = String(auth.currentAppId);
|
|
}
|
|
if (!isMutating(method)) {
|
|
return request(`/web/api/api_${method}`, data ?? {}, extraHeaders);
|
|
}
|
|
begin();
|
|
try {
|
|
return await request(`/web/api/api_${method}`, data ?? {}, extraHeaders);
|
|
} finally {
|
|
end();
|
|
}
|
|
}
|
|
async function consoleApi(path, data) {
|
|
return request(`/console/api/${path}`, data ?? {});
|
|
}
|
|
async function uploadFile(file, path) {
|
|
const contentType = file.type || "application/octet-stream";
|
|
const token = await webApi("getcostoken", { path, filename: file.name, content_type: contentType });
|
|
const uploadUrl = token.upload_url || token.url || "";
|
|
if (!uploadUrl) {
|
|
throw new Error("未获取到上传地址:请确认已在【第三方服务配置→存储】配置并启用「阿里云 OSS」");
|
|
}
|
|
const putResponse = await fetch(uploadUrl, {
|
|
method: "PUT",
|
|
headers: {
|
|
"Content-Type": contentType
|
|
},
|
|
body: file
|
|
});
|
|
if (!putResponse.ok) {
|
|
throw new Error(`Upload failed: ${putResponse.status}`);
|
|
}
|
|
return token.url || uploadUrl.split("?")[0];
|
|
}
|
|
return {
|
|
webApi,
|
|
consoleApi,
|
|
uploadFile
|
|
};
|
|
}
|
|
|
|
export { useApi as u };
|
|
//# sourceMappingURL=useApi-B-E5eLsI.mjs.map
|
|
|