safety-eval-service-frontend/src/api/enterpriseInfo/http.js

100 lines
2.8 KiB
JavaScript
Raw Normal View History

2026-06-23 18:07:30 +08:00
import { Get, Post } from "@cqsjjb/jjb-common-lib/http";
2026-06-25 16:30:37 +08:00
import { normalizeQueryIds, withIds, asId } from "./idUtil";
import { buildOrgInfoHeaders } from "./orgContext";
/**
* jjb-common-lib jjbCommonHttpConfig.header 存在时会完全替换请求头不再读 sessionStorage
* 因此 token / orgInfoId 都通过每次请求的 headers 参数显式传入
*
* @param options.includeOrgContext 默认 true机构 getInfo 查询应传 false不带 orgInfoId
*/
function buildRequestHeaders(extraHeaders = {}, options = {}) {
const { includeOrgContext = true } = options;
const headers = { ...extraHeaders };
const token = sessionStorage.getItem("token");
if (token && !headers.token) {
headers.token = token;
}
if (!includeOrgContext) {
return headers;
}
return buildOrgInfoHeaders(headers);
}
2026-06-23 18:07:30 +08:00
function parseHttpError(err) {
const data = err?.response?.data;
if (data && typeof data === "object") {
return {
success: false,
code: data.code ?? data.errCode,
message: data.message || data.errMessage || "操作失败",
data: data.data ?? null,
};
}
return { success: false, message: err?.message || "请求失败" };
}
/** 底层 HTTP供 adapter 层组合调用(不可嵌套 declareRequest */
2026-06-25 16:30:37 +08:00
export async function apiGet(path, params = {}, headers = {}, options = {}) {
2026-06-23 18:07:30 +08:00
try {
2026-06-25 16:30:37 +08:00
return await Get(path, normalizeQueryIds(params), buildRequestHeaders(headers, options));
2026-06-23 18:07:30 +08:00
}
catch (err) {
return parseHttpError(err);
}
}
/** @ 前缀表示 Post 请求体不包裹 request 字段 */
2026-06-25 16:30:37 +08:00
export async function apiPost(path, data = {}, headers = {}) {
2026-06-23 18:07:30 +08:00
const url = path.startsWith("@") ? path : `@${path}`;
try {
2026-06-25 16:30:37 +08:00
return await Post(url, withIds(data), buildRequestHeaders(headers));
2026-06-23 18:07:30 +08:00
}
catch (err) {
return parseHttpError(err);
}
}
export async function apiPostDelete(path, id) {
2026-06-25 16:30:37 +08:00
const url = `${path}?id=${encodeURIComponent(asId(id) ?? "")}`;
2026-06-23 18:07:30 +08:00
try {
2026-06-25 16:30:37 +08:00
return await Post(url, {}, buildRequestHeaders());
2026-06-23 18:07:30 +08:00
}
catch (err) {
return parseHttpError(err);
}
}
export function safePageResult(mapper) {
return async (params) => {
try {
const res = await mapper(params);
return res;
}
catch (err) {
console.warn("[enterpriseInfo/safePageResult]", err);
return { success: false, data: [], totalCount: 0 };
}
};
}
export function safeAction(mapper) {
return async (params) => {
try {
const res = await mapper(params);
if (res && res.success === false) {
return {
success: false,
message: res.message || res.msg || "操作失败",
code: res.code,
};
}
return res;
}
catch (err) {
console.warn("[enterpriseInfo/safeAction]", err);
return parseHttpError(err);
}
};
}