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

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 });
  }

  /** 统一请求入口:调用共享 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,
    );
  }
}