rpc.ts 2.16 KB
import { createClient } from '@uj/api-core';
import { requestViaHost } from '@uj/platform-sdk';
import { getLoginSession } from '@/access';
import { ensureAccountConfig, getGatewayCredential } from './credentials';
import type { GatewayId, RpcCall } from './types';

// 显式 import 保证任何调用路径下网关策略与 TGT 头策略都已登记。
import './gateways';

/** 老系统统一 3 分钟超时(同 points 的 LEGACY_TIMEOUT)。 */
const LEGACY_TIMEOUT = 180000;

/**
 * 商户域唯一请求出口:与 points / finance 一样走主壳 props.request,请求层保持统一。
 *
 * 差异只用一条声明表达:`hostPolicy: 'legacy-external'`。该策略只关闭主壳为自家 REST
 * 网关准备的两件事 —— RSA 请求头(老 ROP 的 CORS 白名单不认 X-Sign-Algorithm)、
 * Bearer 令牌(老网关用 TGT)。业务码判定**仍留在主壳**:本域网关的 normalize 把老信封
 * 翻成主壳认得的形状(成功 `{ data }`、TGT 失效 `code:401`),主壳的 onLoginRequired
 * 因此会 clearToken + 跳 /login,与全站 401 走同一条登出链路。
 *
 * TGT 按需求取「points 请求用到的 session」——即登录响应 data.loginToken,
 * 由 session.sessionId 注入;api-core 的 'tgt-session' 头策略把它写入全大写 TGT。
 */
export const request = createClient({
  transport: 'host',
  hostSend: requestViaHost(),
  hostPolicy: 'legacy-external',
  timeout: LEGACY_TIMEOUT,
  gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
  gatewayToken: () => '',
  session: {
    sessionId: () => getLoginSession()?.loginToken ?? '',
    paramName: 'sessionId',
  },
  errorHandler: (err) => {
    throw err.cause ?? err;
  },
});

export async function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
  // 网关落点 / appKey / secret 来自配置中心 uj-admin-merchant;首次调用前等它就绪,
  // 避免 prepare 阶段因缺凭据抛错、Network 里看不到任何请求。
  await ensureAccountConfig();
  return request.post<T>(call.method, call.params, {
    gateway: call.gateway,
    signed: call.signed,
    unsignedKeys: call.unsignedKeys,
    noSession: call.noSession,
  });
}