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

/**
 * 请求默认配置类
 */
class Defaults implements RequestConfig {
  baseURL: string;
  timeout: number;
  headers: Record<string, string>;
  appId: string;
  appSecret: string;
  // 重试配置
  retries: number;
  retryDelay: number;
  shouldResetTimeout: boolean;
  // 事件订阅配置
  events: Record<string, Function>;
  // 请求相关
  signal?: AbortSignal;
  method?: string;
  url?: string;
  data?: any;
  responseType?: "json" | "text" | "blob" | "arraybuffer";
  // 其他可选配置
  params?: Record<string, any>;
  signatureFunc?: typeof generateSignature;
  httpOptions?: any;
  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?.dsn) {
      throw new Error("sentry.dsn is required for initialization");
    }

    // 基础配置
    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,
    };

    // 重试配置
    this.retries = config.retries ?? 0; // 默认不重试
    this.retryDelay = config.retryDelay ?? 300; // 默认重试延迟300ms
    this.shouldResetTimeout = config.shouldResetTimeout ?? true; // 默认重试时重置超时

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

    // 其他可选配置
    if (config.params) this.params = { ...config.params };
    if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
    if (config.httpOptions) this.httpOptions = config.httpOptions;

    // 合并其他用户提供的配置
    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 },
    });
  }
}

export default Defaults;