Skip to content

Commit

Permalink
fix: npm types缺失
Browse files Browse the repository at this point in the history
  • Loading branch information
mengxinssfd committed Apr 19, 2022
1 parent 512da2c commit e633585
Show file tree
Hide file tree
Showing 6 changed files with 8 additions and 145 deletions.
2 changes: 1 addition & 1 deletion __test__/Cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Cache from '../src/Cache';
import { Cache } from "../src";
import { sleep } from './utils';
describe('Cache', () => {
test('base', async () => {
Expand Down
3 changes: 1 addition & 2 deletions __test__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import AxiosWrapper from '../src';
import axios from 'axios';
import { routers } from './mock-server';
import { StatusHandlers } from '../src/types';
import { StatusHandlers, AxiosWrapper } from '../src';

jest.mock('axios');
const mockCreate = (/*config: AxiosRequestConfig*/) => {
Expand Down
3 changes: 1 addition & 2 deletions __test__/primary.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// 主域名请求
import { StatusHandlers } from '../src/types';
import AxiosWrapper from '../src';
import { StatusHandlers, AxiosWrapper } from '../src';

const statusHandlers: StatusHandlers = {
200: (res, data, customConfig) => {
Expand Down
2 changes: 1 addition & 1 deletion src/Cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type KeyHandler<K> = (k: K) => string;

export default class Cache<K, V> {
export class Cache<K, V> {
private readonly cache = new Map<string, { value: V; expires: number }>();
private readonly keyHandler: KeyHandler<K>;

Expand Down
143 changes: 4 additions & 139 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,139 +1,4 @@
import type { ResType, CustomConfig } from './types';
import axios, {
AxiosInstance,
AxiosPromise,
AxiosRequestConfig,
AxiosResponse,
Method,
} from 'axios';
import Qs from 'qs';
import Cache from './Cache';

// 使用模板方法模式处理axios请求, 具体类可实现protected方法替换掉原有方法
export default class AxiosWrapper {
private readonly axios: AxiosInstance;
private readonly cache: Cache<AxiosRequestConfig, AxiosPromise>;
constructor(config: AxiosRequestConfig = {}, private customConfig: CustomConfig<boolean> = {}) {
// 1、保存基础配置
this.axios = axios.create(config);
this.setInterceptors();
// 缓存初始化
this.cache = new Cache((config) => {
const url = config.url;
const data = config.data || config.params;
const headers = config.headers;
return JSON.stringify({ url, data, headers });
});
}
// 转换数据结构为ResType
protected transferRes<T>(res: AxiosResponse): ResType<T> {
return res?.data as ResType;
}
// 获取拦截器
protected get interceptors() {
return this.axios.interceptors;
}
protected setInterceptors() {
// 重写此函数会在Request中调用
// example
// this.interceptors.request.use(() => {
// /* do something */
// });
}
protected handleConfig(url: string, config: AxiosRequestConfig): AxiosRequestConfig {
const finalConfig: AxiosRequestConfig = { ...config, url };
finalConfig.method = finalConfig.method || 'get';
return finalConfig;
}
protected handleParams(data: {}, config: AxiosRequestConfig) {
if (config.method === 'get') {
config.params = data;
return;
}
if (!(data instanceof FormData)) {
// 使用Qs.stringify处理过的数据不会有{}包裹
// 使用Qs.stringify其实就是转成url的参数形式:a=1&b=2&c=3
// 格式化模式有三种:indices、brackets、repeat
data = Qs.stringify(data, { arrayFormat: 'repeat' });
}
config.data = data;
}
protected handleResponse<T>(
res: AxiosResponse<ResType<any>>,
data: ResType<any>,
customConfig: CustomConfig<boolean>,
): Promise<ResType<T>> {
const code = data?.code ?? 'default';
const handlers = {
default: (res, data, customConfig) => Promise.reject(customConfig.returnRes ? res : data),
...this.customConfig.statusHandlers,
...customConfig.statusHandlers,
};

const statusHandler = handlers[code] || handlers.default;
return statusHandler(res, data, customConfig as CustomConfig);
}

private _request(customConfig: CustomConfig, axiosConfig: AxiosRequestConfig) {
if (customConfig.useCache) {
const c = this.cache.get(axiosConfig);
if (c) {
return c;
}
}
const res = this.axios(axiosConfig);

const useCache = customConfig.useCache;
if (useCache) {
this.cache.set(axiosConfig, res, typeof useCache === 'object' ? useCache : undefined);
}

return res;
}

request<T = never>(url: string, data?: {}): Promise<ResType<T>>;
request<T = never, RC extends boolean = false>(
url: string,
data?: {},
customConfig?: CustomConfig<RC>,
axiosConfig?: AxiosRequestConfig,
): Promise<RC extends true ? AxiosResponse<ResType<T>> : ResType<T>>;
async request<T>(
url: string,
data: {} = {},
customConfig: CustomConfig = {},
axiosConfig: AxiosRequestConfig = {},
): Promise<any> {
// 1、处理配置
const config = this.handleConfig(url, axiosConfig);
// 2、处理参数
this.handleParams(data, config);
try {
// 3、请求
const response: AxiosResponse = await this._request(customConfig, config);
// 4、请求结果数据结构处理
const data = this.transferRes<T>(response);
// 5、状态码处理,并返回结果
return this.handleResponse<T>(response, data, customConfig);
} catch (e: any) {
// 错误处理
const response: AxiosResponse<ResType<any>> = e.response;
const data = this.transferRes<T>(response);
if (data && data.code !== undefined) {
return this.handleResponse<T>(response, data, customConfig);
}
throw e;
}
}

static methodFactory(method: Method, ins: AxiosWrapper) {
return function <T = never, RC extends boolean = false>(
url: string,
data?: {},
customConfig?: CustomConfig<RC>,
axiosConfig?: AxiosRequestConfig,
) {
return ins.request<T, RC>(url, data, customConfig, { ...axiosConfig, method });
};
}
}
export * from './AxiosWrapper';
export * from './Cache';
export * from './HttpStatus';
export * from './types';
File renamed without changes.

0 comments on commit e633585

Please sign in to comment.