client.ts 2.21 KB
// API 基类:所有业务子类共享同一个已挂载 RSA 加签/验签拦截器的 http 实例,
// 并复用统一的 get/post/put/del 请求方法(自动解包响应体 data 字段)。
// 规范见《优加门店上架系统 · 前后端 RSA 非对称加签对接说明》。
import { http } from './http';
import type { ApiResult } from './types';
import type { AxiosResponseHeaders } from 'axios';

export interface BlobResponse {
  blob: Blob;
  headers: Record<string, string> | AxiosResponseHeaders;
}

export class ApiClient {
  /** 共享的 axios 实例(请求加签 / 响应验签在 ./http 拦截器中完成) */
  protected readonly http = http;

  protected get<T>(url: string, params?: Record<string, unknown>): Promise<T> {
    return this.call<T>('GET', url, { params });
  }

  protected post<T>(url: string, data?: unknown): Promise<T> {
    return this.call<T>('POST', url, { data });
  }

  protected put<T>(url: string, data?: unknown): Promise<T> {
    return this.call<T>('PUT', url, { data });
  }

  protected del<T>(url: string, params?: Record<string, unknown>): Promise<T> {
    return this.call<T>('DELETE', url, { params });
  }

  /** 下载二进制文件(不解包 data,直接返回原始 blob + response headers(含 content-disposition)) */
  protected async getBlob(url: string, params?: Record<string, unknown>): Promise<BlobResponse> {
    // 注意:经过 http.ts 响应拦截器后,非 JSON(文件流)分支会返回 {data: Blob, headers} 包装体(与原生 resp 形状一致)
    // 详见 src/api/core/http.ts 响应拦截器「非 JSON 分支」
    const resp = (await this.http.request({
      method: 'GET',
      url,
      params,
      responseType: 'blob',
    })) as unknown as { data: Blob; headers: Record<string, string> };
    return {
      blob: resp.data,
      headers: resp.headers ?? {},
    };
  }

  /** 统一请求入口:调用共享 http,并把响应 body 解包为 data */
  private call<T>(method: string, url: string, extra: Record<string, unknown> = {}): Promise<T> {
    const config = { method, url, ...extra } as any;
    return (this.http.request<ApiResult<T>>(config) as unknown as Promise<ApiResult<T>>).then(
      (res) => res.data,
    );
  }
}