rpc.ts 3.03 KB
/*
 * @Author: liimin 17653212@qq.com
 * @Date: 2026-11-06 17:31:14
 * @LastEditors: liimin 17653212@qq.com
 * @LastEditTime: 2026-11-09 18:47:44
 * @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\rpc.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createClient } from '@uj/api-core';
import { requestViaHost } from '@uj/platform-sdk';
import { getLoginSession } from '@/access';
// 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记,
// 否则 resolveGateway 会抛「网关尚未接入」。
import './gateways';
import { getGatewayCredential, getGatewayToken } from './credentials';
import type { GatewayId, RpcCall } from './types';

/** 老系统的 RPC 网关统一 3 分钟超时(原 config 的 request.timeout: 180000)。 */
const LEGACY_TIMEOUT = 180000;

/**
 * web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。
 *
 * createClient({配置}) 不传 kind 即最新版方案(rpcGateway);fixedParams 合并、
 * 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定,
 * 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。
 * 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend),
 * 门面不打包 axios,请求仍交回主壳那唯一一份实例。
 *
 * 装配层只给环境参数:
 *  · gatewayCredential / gatewayToken —— 本域 .env 凭据与会话令牌,包内不留密钥字面量;
 *  · contentType:false —— 不预置 Content-Type,否则会改变主壳加签的 canonical 原文;
 *  · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
 *    保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
 */
export const request = createClient({
  transport: 'host',
  hostSend: requestViaHost(),
  timeout: LEGACY_TIMEOUT,
  contentType: false,
  gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
  gatewayToken: getGatewayToken,
  // sessionId 取自登录接口的 data.loginToken(老网关会话标识);facade 的 resolveSession 会在
  // 签名前把它并入请求体并参与 SHA1 加签(与老系统请求体一致)。source 作为网关级固定参数已登记在
  // 网关策略(glsx.ts 的 GatewayStrategy.fixedParams)里,这里无需重复配置。
  session: {
    sessionId: () => getLoginSession()?.loginToken ?? '',
    paramName: 'sessionId',
  },
  errorHandler: (err) => {
    throw err.cause ?? err;
  },
});

/** 业务语义调用 → 门面只传参;rpcCall 的公开签名不变,业务模块零改动。 */
export function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
  return request.post<T>(call.method, call.params, {
    gateway: call.gateway,
    signed: call.signed,
    unsignedKeys: call.unsignedKeys,
  });
}