defaults.ts 2.98 KB
import type { RequestConfig, ResponseConfig, RetryConfig } from "../types";
import { generateSignature } from "../security/signature";

/**
 * 请求默认配置类
 */
class Defaults implements RequestConfig {
  baseURL: string;
  timeout: number;
  headers: Record<string, string>;
  appId: string;
  appSecret: string;
  // 重试配置
  retry?: RetryConfig;
  // 事件订阅配置
  events: Record<string, Function>;
  // 请求相关
  signal?: AbortSignal;
  method?: string;
  url?: string;
  data?: any;
  responseType?: "json" | "text" | "blob" | "arraybuffer";
  // 其他可选配置
  params?: Record<string, any>;
  signatureFunc?: typeof generateSignature;
  response?: ResponseConfig;
  returnAll?: boolean;
  // Sentry 配置
  sentry: {
    enable: boolean;
    dsn?: string;
    options?: Record<string, any>;
  };
  // 安全配置
  security: {
    enable: boolean;
    address?: string;
  };

  /**
   * 创建默认配置实例
   * @param config 用户提供的配置
   */
  constructor(config: Partial<RequestConfig> = {}) {
    // 检查必填参数
    if (config.sentry?.enable && !config.sentry?.dsn) {
      throw new Error("sentry.dsn is required when sentry is enabled");
    }
    // 基础配置
    this.baseURL = config.baseURL || "";
    this.timeout = config.timeout || 5000;
    this.headers = {
      "Content-Type": "application/json;charset=UTF-8",
      ...config.headers,
    };
    this.appId = config.appId || "";
    this.appSecret = config.appSecret || "";
    this.sentry = {
      enable: config.sentry?.enable ?? false,
      dsn: config.sentry?.dsn,
      options: config.sentry?.options || {},
    };
    this.security = {
      enable: config.security?.enable ?? false,
      address: config.security?.address,
    };

    // 重试配置
    if (config.retry) {
      this.retry = config.retry;
    }

    // 事件订阅配置
    this.events = config.events || {};

    // 其他可选配置
    if (config.params) this.params = { ...config.params };
    if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
    if (config.response) this.response = config.response;
    if (config.returnAll !== undefined) this.returnAll = config.returnAll;

    // 合并其他用户提供的配置
    Object.keys(config).forEach((key) => {
      if (!(key in this)) {
        (this as any)[key] = (config as any)[key];
      }
    });
  }

  /**
   * 创建新的配置实例,合并当前配置和新配置
   * @param config 要合并的新配置
   * @returns 新的配置实例
   */
  merge(config: Partial<RequestConfig> = {}): Defaults {
    return new Defaults({
      ...this,
      ...config,
      // 确保params正确合并
      params: { ...this.params, ...config.params },
      // 确保headers正确合并
      headers: { ...this.headers, ...config.headers },
      // 确保response正确合并
      response: { ...this.response, ...config.response },
      // 确保retry正确合并
      retry: { ...this.retry, ...config.retry }
    });
  }
}

export default Defaults;