100 lines
2.8 KiB
JavaScript
100 lines
2.8 KiB
JavaScript
import { Get, Post } from "@cqsjjb/jjb-common-lib/http";
|
||
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);
|
||
}
|
||
|
||
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) */
|
||
export async function apiGet(path, params = {}, headers = {}, options = {}) {
|
||
try {
|
||
return await Get(path, normalizeQueryIds(params), buildRequestHeaders(headers, options));
|
||
}
|
||
catch (err) {
|
||
return parseHttpError(err);
|
||
}
|
||
}
|
||
|
||
/** @ 前缀表示 Post 请求体不包裹 request 字段 */
|
||
export async function apiPost(path, data = {}, headers = {}) {
|
||
const url = path.startsWith("@") ? path : `@${path}`;
|
||
try {
|
||
return await Post(url, withIds(data), buildRequestHeaders(headers));
|
||
}
|
||
catch (err) {
|
||
return parseHttpError(err);
|
||
}
|
||
}
|
||
|
||
export async function apiPostDelete(path, id) {
|
||
const url = `${path}?id=${encodeURIComponent(asId(id) ?? "")}`;
|
||
try {
|
||
return await Post(url, {}, buildRequestHeaders());
|
||
}
|
||
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);
|
||
}
|
||
};
|
||
}
|