Commit 46f77d94 by chenwq

优化 API 客户端,重构请求处理逻辑,增强门店数据解析功能

1 parent ef278720
...@@ -6,12 +6,42 @@ import { loadUsedcarGscConfig, loadUsedcarRemoteConfig } from './config-center'; ...@@ -6,12 +6,42 @@ import { loadUsedcarGscConfig, loadUsedcarRemoteConfig } from './config-center';
export class ApiClient { export class ApiClient {
protected async post<T>(url: string, data: Record<string, unknown> = {}): Promise<T> { protected async post<T>(url: string, data: Record<string, unknown> = {}): Promise<T> {
const value = await loadUsedcarGscConfig(); const value = await loadUsedcarGscConfig();
return createClient({ kind: 'gsc', transport: 'host', hostSend: requestViaHost(), baseURL: value.baseURL, appKey: value.appId, appSecret: value.appSecret, session: { sessionId: () => getLoginSession()?.loginToken ?? '', paramName: 'sessionId' }, errorHandler: (error) => { throw error.cause ?? error; } }).post<T>(url, data); return createClient({
kind: 'gsc',
transport: 'host',
hostSend: requestViaHost(),
baseURL: value.baseURL,
appKey: value.appId,
appSecret: value.appSecret,
session: { sessionId: () => getLoginSession()?.loginToken ?? '', paramName: 'sessionId' },
errorHandler: (error) => {
throw error.cause ?? error;
},
}).post<T>(url, data);
} }
protected async postRop<T>(method: string, data: Record<string, unknown> = {}): Promise<T> { protected async postRop<T>(method: string, data: Record<string, unknown> = {}): Promise<T> {
const { axios } = await loadUsedcarRemoteConfig(); const { axios } = await loadUsedcarRemoteConfig();
const router = new URL(axios.baseURL); const endpoint = axios.baseURL;
const path = router.pathname.replace(/router$/, ''); const body = {
return createClient({ kind: 'rop', transport: 'host', hostSend: requestViaHost(), baseURL: router.origin, path, hostType: 'dj', djSecretKey: { appKey: axios.appkey, secret: axios.secret }, session: { sessionId: () => getLoginSession()?.loginToken ?? '', paramName: 'sessionId' }, errorHandler: (error) => { throw error.cause ?? error; } }).post<T>(method, data); ...data,
method,
timestamp: Date.now(),
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
sessionId: getLoginSession()?.loginToken ?? '',
};
return createClient({
kind: 'rest',
transport: 'host',
hostSend: requestViaHost(),
appKey: axios.appkey,
appSecret: axios.secret,
contentType: 'application/x-www-form-urlencoded',
signature: 'sha1',
errorHandler: (error) => {
throw error.cause ?? error;
},
}).post<T>(endpoint, body);
} }
} }
...@@ -6,6 +6,10 @@ class DashboardApi extends ApiClient { ...@@ -6,6 +6,10 @@ class DashboardApi extends ApiClient {
getdataBoard(params: Record<string, unknown>) { return this.post<DashboardStatistics>('/dataBoard/index', params); } getdataBoard(params: Record<string, unknown>) { return this.post<DashboardStatistics>('/dataBoard/index', params); }
getEvaluationData(params: Record<string, unknown>) { return this.post<TrendPoint[]>('/dataBoard/evaluation', params); } getEvaluationData(params: Record<string, unknown>) { return this.post<TrendPoint[]>('/dataBoard/evaluation', params); }
getDealData(params: Record<string, unknown>) { return this.post<TrendPoint[]>('/dataBoard/deal', params); } getDealData(params: Record<string, unknown>) { return this.post<TrendPoint[]>('/dataBoard/deal', params); }
getServiceStore(params: Record<string, unknown>) { return this.postRop<StoreItem[]>('dj.api.scenemerchantref.query4SRefByYqShop', params); } async getServiceStore(params: Record<string, unknown>) {
const response = await this.postRop<StoreItem[]>('dj.api.scenemerchantref.query4SRefByYqShop', params);
console.log('[usedcar] 门店接口原始返回:', response);
return response;
}
} }
export const dashboardApi = new DashboardApi(); export const dashboardApi = new DashboardApi();
...@@ -23,6 +23,39 @@ const STATS = [ ...@@ -23,6 +23,39 @@ const STATS = [
['新车交付数(辆)', 'newCarDeliveryCount', 'newCarDeliveryCountChainRatio'], ['新车交付数(辆)', 'newCarDeliveryCount', 'newCarDeliveryCountChainRatio'],
['二手车收购交车数(辆)', 'acquisitionDeliveryCount', 'acquisitionDeliveryCountChainRatio'], ['二手车收购交车数(辆)', 'acquisitionDeliveryCount', 'acquisitionDeliveryCountChainRatio'],
] as const; ] as const;
function storesFromResponse(response: unknown): Array<{ merchantId: string; merchantName: string }> {
function parse(value: unknown): unknown {
if (typeof value !== 'string') return value;
try {
return JSON.parse(value) as unknown;
} catch {
return value;
}
}
function findList(value: unknown, depth = 0): unknown[] | undefined {
const parsed = parse(value);
if (parsed !== value) return findList(parsed, depth + 1);
if (Array.isArray(parsed)) return parsed;
if (!parsed || typeof parsed !== 'object' || depth > 4) return undefined;
const record = parsed as Record<string, unknown>;
for (const key of ['list', 'records', 'content', 'data', 'result']) {
const found = findList(record[key], depth + 1);
if (found) return found;
}
return undefined;
}
const list = findList(response);
if (!Array.isArray(list)) return [];
return list
.map((item) => {
const store = item as Record<string, unknown>;
return {
merchantId: String(store.merchantId ?? store.shopMerchantId ?? store.merchantNo ?? ''),
merchantName: String(store.merchantName ?? store.shopMerchantName ?? store.merchantNo ?? ''),
};
})
.filter((item) => item.merchantId && item.merchantName);
}
function Trend({ title, load }: { title: string; load: (type: number) => Promise<TrendPoint[]> }) { function Trend({ title, load }: { title: string; load: (type: number) => Promise<TrendPoint[]> }) {
const [type, setType] = useState(1); const [type, setType] = useState(1);
const query = useQuery({ queryKey: ['trend', title, type], queryFn: () => load(type) }); const query = useQuery({ queryKey: ['trend', title, type], queryFn: () => load(type) });
...@@ -60,7 +93,11 @@ export default function Dashboard() { ...@@ -60,7 +93,11 @@ export default function Dashboard() {
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null); const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
const stores = useQuery({ const stores = useQuery({
queryKey: ['stores'], queryKey: ['stores'],
queryFn: () => dashboardApi.getServiceStore({ scene: 7 }), queryFn: async () => {
const response = await dashboardApi.getServiceStore({ scene: 7 });
console.info('[usedcar] 门店接口原始返回:', response);
return storesFromResponse(response);
},
}); });
const params = useMemo( const params = useMemo(
() => ({ () => ({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!