1.0.0 • Published 2 years ago

@pagoda-tools/api v1.0.0

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

PagodaCos

示例代码

import { createApiService } from '@pagoda-tools/api';
import axios from 'axios';

const http = axios.create();

const createApi = createApiService(http);

createApi({
  url: 'xxx',
  method: 'get',
}).request({
  body: {},
});

API

createApiService

interface ApiConfig {
  url: string | ((path: ApiRequestConfig['path']) => string);
  method: Method;
  cache: boolean;
  cacheTime: number;
  headers: AxiosRequestConfig['headers'];
  axiosConfig: AxiosRequestConfig;
}

interface ApiRequestConfig<T = any> {
  headers?: AxiosRequestConfig<T>['headers'];
  path?: Record<string, string>;
  query?: Record<string, string>;
  body?: AxiosRequestConfig<T>['data'];
  axiosConfig?: AxiosRequestConfig<T>;
}

class Api {
  http: AxiosInstance;

  config: ApiConfig;

  cache: Record<
    string,
    {
      promise: Promise<any>;
      expireTime: number | null;
    }
  >;

  constructor(http: AxiosInstance, config: ApiConfig): Api;

  request<T = never, R = AxiosResponse<T>>(
    requestConfig?: ApiRequestConfig<T>
  ): Promise<R>;

  clearCache(): void;
}

function createApiService(http: AxiosInstance): (apiConfig: ApiConfig) => Api;