index.ts 7.32 KB
/**
 * 兼容旧版 Vue 项目的 ROP 接口客户端。
 *
 * 它与 ../core 的 REST + RSA 客户端完全独立:不复用其签名、登录凭证或拦截器。
 * ROP 服务通常只有一个路由入口,通过请求参数中的 method 区分业务接口。
 */
import axios, { type AxiosAdapter, type AxiosRequestConfig, type Method } from 'axios';
import { KJUR } from 'jsrsasign';

export type RopSignWay = 'sha1' | 'md5';
export type RopRequestMethod = 'get' | 'post' | 'put' | 'delete';
export type RopPayload = Record<string, unknown>;

export interface RopResultRule {
  /** 返回状态字段,默认 code */
  codeKey?: string;
  /** 成功状态值,默认 0 */
  successCode?: string | number;
  /** 业务数据字段,默认 data */
  dataKey?: string;
  /** 错误说明字段,默认 message */
  messageKey?: string;
}

export interface RopClientConfig {
  /** ROP 路由入口地址,例如 https://example.com/router */
  baseURL: string;
  appKey: string;
  /** ROP 共享密钥;请通过环境配置提供,不要写入业务页面。 */
  secret: string;
  signWay?: RopSignWay;
  timeout?: number;
  /** 非登录请求自动附带的会话标识。 */
  getSessionId?: () => string | null | undefined;
  /** 默认 dj.api.user.login;该接口不附带 sessionId。 */
  loginMethod?: string;
  result?: RopResultRule;
  /** 测试或特殊网络场景可替换发送适配器。 */
  adapter?: AxiosAdapter;
  /** 仅用于测试;生产环境默认取当前时间。 */
  now?: () => number;
}

export interface RopRequestOptions {
  /** 返回服务端完整内容;默认只返回 data。 */
  returnAll?: boolean;
  signal?: AbortSignal;
  headers?: Record<string, string>;
  onUploadProgress?: AxiosRequestConfig['onUploadProgress'];
}

interface RequiredRopResultRule {
  codeKey: string;
  successCode: string | number;
  dataKey: string;
  messageKey: string;
}

const DEFAULT_RESULT_RULE: RequiredRopResultRule = {
  codeKey: 'code',
  successCode: 0,
  dataKey: 'data',
  messageKey: 'message',
};

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return Object.prototype.toString.call(value) === '[object Object]';
}

/**
 * 按旧 Vue 项目 qs.stringify({ arrayFormat: 'indices', allowDots: true }) 的字段命名展开对象。
 * undefined 会被旧实现的 JSON 深拷贝忽略;null 会作为空字符串参与签名。
 */
function flattenPayload(
  value: unknown,
  prefix = '',
  output: Record<string, string> = {},
): Record<string, string> {
  if (value === undefined) return output;
  if (value === null) {
    output[prefix] = '';
    return output;
  }
  if (Array.isArray(value)) {
    value.forEach((item, index) => flattenPayload(item, `${prefix}[${index}]`, output));
    return output;
  }
  if (isPlainObject(value)) {
    Object.keys(value).forEach((key) => {
      flattenPayload(value[key], prefix ? `${prefix}.${key}` : key, output);
    });
    return output;
  }
  output[prefix] = String(value);
  return output;
}

function normalizePayload(payload: RopPayload): Record<string, string> {
  // 旧版实现先 JSON 深拷贝;这里保留相同的 undefined 忽略行为,且不修改调用方对象。
  return flattenPayload(payload);
}

/** 按 ROP 旧规则生成签名后的平铺参数。 */
export function signRopPayload(
  payload: RopPayload,
  config: Pick<RopClientConfig, 'secret' | 'signWay'>,
  noSignAttrs: readonly string[] = [],
): Record<string, string> {
  const params = normalizePayload(payload);
  delete params.sign;
  const sortedKeys = Object.keys(params).sort();
  const canonical = sortedKeys
    .filter((key) => !noSignAttrs.includes(key))
    .map((key) => key + params[key])
    .join('');
  const signWay = config.signWay ?? 'sha1';
  params.sign = KJUR.crypto.Util.hashString(
    config.secret + canonical + config.secret,
    signWay,
  ).toUpperCase();
  return params;
}

function toFormBody(params: Record<string, string>): string {
  return new URLSearchParams(params).toString();
}

function resolveResponse<T>(body: unknown, rule: RequiredRopResultRule, returnAll: boolean): T {
  if (returnAll) return body as T;
  if (!isPlainObject(body)) throw new Error('ROP 接口返回内容格式不正确');
  const code = body[rule.codeKey] ?? body.returnCode;
  const message = body[rule.messageKey];
  if (String(code) !== String(rule.successCode)) {
    const error = new Error(
      typeof message === 'string' && message ? message : 'ROP 接口请求失败',
    ) as Error & { code?: unknown; data?: unknown };
    error.code = code;
    error.data = body[rule.dataKey];
    throw error;
  }
  return body[rule.dataKey] as T;
}

export interface RopClient {
  request<T>(
    method: RopRequestMethod,
    payload: RopPayload,
    options?: RopRequestOptions,
    noSignAttrs?: readonly string[],
  ): Promise<T>;
  get<T>(
    payload: RopPayload,
    options?: RopRequestOptions,
    noSignAttrs?: readonly string[],
  ): Promise<T>;
  post<T>(
    payload: RopPayload,
    options?: RopRequestOptions,
    noSignAttrs?: readonly string[],
  ): Promise<T>;
  put<T>(
    payload: RopPayload,
    options?: RopRequestOptions,
    noSignAttrs?: readonly string[],
  ): Promise<T>;
  del<T>(
    payload: RopPayload,
    options?: RopRequestOptions,
    noSignAttrs?: readonly string[],
  ): Promise<T>;
}

/**
 * 创建独立的 ROP 客户端。每个旧系统可传入自己的地址、appKey 与密钥,互不影响。
 */
export function createRopClient(config: RopClientConfig): RopClient {
  const http = axios.create({
    baseURL: config.baseURL,
    timeout: config.timeout ?? 100000,
    adapter: config.adapter,
  });
  const resultRule: RequiredRopResultRule = { ...DEFAULT_RESULT_RULE, ...config.result };
  const loginMethod = config.loginMethod ?? 'dj.api.user.login';
  const now = config.now ?? Date.now;

  async function request<T>(
    method: RopRequestMethod,
    payload: RopPayload,
    options: RopRequestOptions = {},
    noSignAttrs: readonly string[] = [],
  ): Promise<T> {
    const common: RopPayload = {
      ...payload,
      appKey: config.appKey,
      timestamp: now(),
      v: '1.0.0',
      format: 'json',
      locale: 'zh_CN',
    };
    if (payload.method !== loginMethod) {
      const sessionId = config.getSessionId?.();
      if (sessionId) common.sessionId = sessionId;
    }
    const signed = signRopPayload(common, config, noSignAttrs);
    const requestConfig: AxiosRequestConfig = {
      method: method as Method,
      signal: options.signal,
      headers: options.headers,
      onUploadProgress: options.onUploadProgress,
    };
    if (method === 'get' || method === 'delete') {
      requestConfig.params = signed;
    } else {
      requestConfig.data = toFormBody(signed);
      requestConfig.headers = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        ...options.headers,
      };
    }
    const response = await http.request(requestConfig);
    return resolveResponse<T>(response.data, resultRule, options.returnAll === true);
  }

  return {
    request,
    get: (payload, options, noSignAttrs) => request('get', payload, options, noSignAttrs),
    post: (payload, options, noSignAttrs) => request('post', payload, options, noSignAttrs),
    put: (payload, options, noSignAttrs) => request('put', payload, options, noSignAttrs),
    del: (payload, options, noSignAttrs) => request('delete', payload, options, noSignAttrs),
  };
}