🎨 优化

pull/1/head
zhujunxian 2020-04-22 17:05:27 +08:00
parent 67c9b49976
commit 7b20ad9661
15 changed files with 112 additions and 60 deletions

16
.editorconfig Executable file
View File

@ -0,0 +1,16 @@
# http://editorconfig.org
# root = true
# [*]
# indent_style = space
# indent_size = 2
# end_of_line = lf
# charset = utf-8
# trim_trailing_whitespace = true
# insert_final_newline = true
# [*.md]
# trim_trailing_whitespace = false
# [Makefile]
# indent_style = tab

View File

@ -501,4 +501,18 @@ const instance = new axios.Axios({
instance.get('/test'); instance.get('/test');
``` ```
## 执行流程
```typescript
axios('/test').then().catch();
// 请求成功
// axios => axios.interceptors.request => config.transformRequest => config.paramsSerializer => config.adapter => config.validateStatus => config.transformResponse => axios.interceptors.response => then
// 请求失败
// axios => axios.interceptors.request => config.transformRequest => config.paramsSerializer => config.adapter => config.validateStatus => config.transformResponse => config.errorHandler => axios.interceptors.response => catch
```
## Typescript
![avatar](http://chuantu.xyz/t6/730/1587543726x1700338641.jpg)

View File

@ -1,6 +1,6 @@
{ {
"name": "axios-miniprogram", "name": "axios-miniprogram",
"version": "1.1.1", "version": "1.1.2",
"description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。", "description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。",
"main": "package/index.js", "main": "package/index.js",
"miniprogram": "package", "miniprogram": "package",

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-17 12:18:25 * @Date: 2020-04-17 12:18:25
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-22 09:37:49 * @LastEditTime: 2020-04-22 13:24:28
*/ */
import { Adapter, Platform } from './types'; import { Adapter, Platform } from './types';
@ -34,21 +34,13 @@ const stack = [
function adaptive(): Adapter | undefined { function adaptive(): Adapter | undefined {
let adapter: Adapter | undefined; let adapter: Adapter | undefined;
const platform = stack.shift(); while (stack.length !== 0 && adapter === undefined) {
try {
if (platform === undefined) { adapter = (stack.shift() as () => Adapter | undefined)();
return; } catch (err) {}
} }
try { return adapter;
adapter = platform();
} catch (err) {}
if (adapter !== undefined) {
return adapter;
}
return adaptive();
} }
export default adaptive; export default adaptive;

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-15 12:45:18 * @Date: 2020-04-15 12:45:18
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-21 14:38:43 * @LastEditTime: 2020-04-22 16:07:56
*/ */
import { AxiosRequestConfig, Data, AxiosResponse, AxiosBaseInstance, AxiosInstance } from './types'; import { AxiosRequestConfig, Data, AxiosResponse, AxiosBaseInstance, AxiosInstance } from './types';
import Axios from './core/Axios'; import Axios from './core/Axios';
@ -78,3 +78,19 @@ axios.CancelToken = CancelToken;
axios.isCancel = isCancel; axios.isCancel = isCancel;
export default axios; export default axios;
// axios
// .extractData<{}>(
// axios.get(
// '/test',
// {
// id: 1,
// },
// {
// headers: { aaa: 'aaa' },
// }
// )
// )
// .then((data) => {
// console.log(data);
// });

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-13 18:00:27 * @Date: 2020-04-13 18:00:27
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-21 20:19:49 * @LastEditTime: 2020-04-22 15:59:22
*/ */
import { Method, Params, Data, Interceptors, AxiosRequestConfig, AxiosResponse, Axios } from '../types'; import { Method, Params, Data, Interceptors, AxiosRequestConfig, AxiosResponse, Axios } from '../types';
import buildURL from '../helpers/buildURL'; import buildURL from '../helpers/buildURL';

6
src/core/extractData.ts Normal file
View File

@ -0,0 +1,6 @@
/*
* @Author: early-autumn
* @Date: 2020-04-22 15:59:25
* @LastEditors: early-autumn
* @LastEditTime: 2020-04-22 15:59:42
*/

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-16 00:48:45 * @Date: 2020-04-16 00:48:45
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-21 09:49:45 * @LastEditTime: 2020-04-22 16:02:22
*/ */
import { AxiosRequestConfig, AxiosResponse, Response } from '../types'; import { AxiosRequestConfig, AxiosResponse, Response } from '../types';
import transformRequest from './transformRequest'; import transformRequest from './transformRequest';

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-17 14:09:16 * @Date: 2020-04-17 14:09:16
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-20 09:05:01 * @LastEditTime: 2020-04-22 13:06:27
*/ */
import { AxiosRequestConfig, AxiosResponse, Response } from '../types'; import { AxiosRequestConfig, AxiosResponse, Response } from '../types';
import { pick } from '../helpers/utils'; import { pick } from '../helpers/utils';
@ -20,13 +20,12 @@ export default function transformResponse(response: Response, config: AxiosReque
const status = response.statusCode ?? response.status ?? 400; const status = response.statusCode ?? response.status ?? 400;
const headers = response.header ?? response.headers ?? {}; const headers = response.header ?? response.headers ?? {};
const statusText = status === 200 ? 'OK' : status === 400 ? 'Bad Adapter' : ''; const statusText = status === 200 ? 'OK' : status === 400 ? 'Bad Adapter' : '';
const pickResponse = pick<Response, 'data' | 'cookies' | 'profile'>(response, 'data', 'cookies', 'profile');
return { return {
status, status,
statusText, statusText,
headers, headers,
config, config,
...pickResponse, ...pick<Response, 'data' | 'cookies' | 'profile'>(response, 'data', 'cookies', 'profile'),
}; };
} }

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-13 21:45:45 * @Date: 2020-04-13 21:45:45
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-20 21:21:23 * @LastEditTime: 2020-04-22 15:51:28
*/ */
import { AnyObject, Params } from '../types'; import { AnyObject, Params } from '../types';
import { encode, isPlainObject, isDate } from './utils'; import { encode, isPlainObject, isDate } from './utils';
@ -16,6 +16,7 @@ import { encode, isPlainObject, isDate } from './utils';
function generateURL(url: string, serializedParams: string): string { function generateURL(url: string, serializedParams: string): string {
// 移除 hash // 移除 hash
const hashIndex = url.indexOf('#'); const hashIndex = url.indexOf('#');
if (hashIndex !== -1) { if (hashIndex !== -1) {
url = url.slice(0, hashIndex); url = url.slice(0, hashIndex);
} }
@ -26,9 +27,10 @@ function generateURL(url: string, serializedParams: string): string {
// 拼接前缀 // 拼接前缀
const prefix = url.indexOf('?') === -1 ? '?' : '&'; const prefix = url.indexOf('?') === -1 ? '?' : '&';
serializedParams = `${prefix}${serializedParams}`; serializedParams = `${prefix}${serializedParams}`;
return `${url.replace(/\/*$/, '')}${serializedParams}`; return `${url}${serializedParams}`;
} }
/** /**
@ -39,7 +41,7 @@ function generateURL(url: string, serializedParams: string): string {
function paramsSerialization(params: AnyObject): string { function paramsSerialization(params: AnyObject): string {
const parts: string[] = []; const parts: string[] = [];
Object.entries(params).forEach(([key, value]): void => { Object.entries(params).forEach(function encodeKeyValue([key, value]): void {
if (value === null || value === undefined || value !== value) { if (value === null || value === undefined || value !== value) {
return; return;
} }

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-13 21:55:40 * @Date: 2020-04-13 21:55:40
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-20 10:24:00 * @LastEditTime: 2020-04-22 13:02:06
*/ */
import { AnyObject } from '../types'; import { AnyObject } from '../types';
@ -68,8 +68,10 @@ export function deepMerge(...objs: Record<string, any>[]): Record<string, any> {
} }
} }
objs.forEach((obj: Record<string, any>): void => { objs.forEach(function assignObj(obj: Record<string, any>): void {
Object.entries(obj).forEach(([key, value]) => assignValue(key, value)); Object.entries(obj).forEach(function assignKey([key, value]) {
assignValue(key, value);
});
}); });
return result; return result;

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-14 23:22:52 * @Date: 2020-04-14 23:22:52
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-19 02:31:59 * @LastEditTime: 2020-04-22 16:42:48
*/ */
import axios from './axios'; import axios from './axios';

View File

@ -2,8 +2,11 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-13 15:23:53 * @Date: 2020-04-13 15:23:53
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-21 14:38:31 * @LastEditTime: 2020-04-22 16:08:07
*/ */
import axios from './axios';
/** /**
* *
*/ */
@ -37,7 +40,7 @@ export declare type Data = string | AnyObject | ArrayBuffer;
/** /**
* Axios * Axios
*/ */
export interface Headers { export declare interface Headers {
/** /**
* *
*/ */
@ -92,7 +95,7 @@ export interface Headers {
/** /**
* *
*/ */
export interface RequestConfig { export declare interface RequestConfig {
/** /**
* *
*/ */
@ -157,7 +160,7 @@ export interface RequestConfig {
/** /**
* *
*/ */
export interface Response { export declare interface Response {
/** /**
* *
*/ */
@ -197,7 +200,7 @@ export interface Response {
/** /**
* *
*/ */
export interface AdapterRequestConfig extends RequestConfig { export declare interface AdapterRequestConfig extends RequestConfig {
/** /**
* *
*/ */
@ -212,7 +215,7 @@ export interface AdapterRequestConfig extends RequestConfig {
/** /**
* *
*/ */
export interface AdapterRequestTask { export declare interface AdapterRequestTask {
/** /**
* *
*/ */
@ -222,28 +225,28 @@ export interface AdapterRequestTask {
/** /**
* *
*/ */
export interface Adapter { export declare interface Adapter {
(config: AdapterRequestConfig): AdapterRequestTask | void; (config: AdapterRequestConfig): AdapterRequestTask | void;
} }
/** /**
* *
*/ */
export interface Platform { export declare interface Platform {
request: Adapter; request: Adapter;
} }
/** /**
* *
*/ */
export interface TransformData { export declare interface TransformData {
(data: Data, headers: Headers): Data; (data: Data, headers: Headers): Data;
} }
/** /**
* *
*/ */
export interface ErrorHandler { export declare interface ErrorHandler {
(error: any): Promise<any> | any; (error: any): Promise<any> | any;
} }
@ -355,7 +358,7 @@ export declare interface AxiosRequestConfig {
/** /**
* Axios * Axios
*/ */
export interface AxiosResponse<T extends Data = Data> { export declare interface AxiosResponse<T extends Data = Data> {
/** /**
* *
*/ */
@ -395,21 +398,21 @@ export interface AxiosResponse<T extends Data = Data> {
/** /**
* *
*/ */
export interface InterceptorResolved<T = any> { export declare interface InterceptorResolved<T = any> {
(value: T): Promise<T> | T; (value: T): Promise<T> | T;
} }
/** /**
* *
*/ */
export interface InterceptorRejected { export declare interface InterceptorRejected {
(error: any): Promise<any> | any; (error: any): Promise<any> | any;
} }
/** /**
* *
*/ */
export interface Interceptor<T = any> { export declare interface Interceptor<T = any> {
/** /**
* *
*/ */
@ -423,14 +426,14 @@ export interface Interceptor<T = any> {
/** /**
* *
*/ */
export interface InterceptorExecutor<T = any> { export declare interface InterceptorExecutor<T = any> {
(interceptor: Interceptor<T>): void; (interceptor: Interceptor<T>): void;
} }
/** /**
* *
*/ */
export interface InterceptorManager<T = any> { export declare interface InterceptorManager<T = any> {
/** /**
* *
* *
@ -458,7 +461,7 @@ export interface InterceptorManager<T = any> {
/** /**
* Axios * Axios
*/ */
export interface Interceptors { export declare interface Interceptors {
/** /**
* request * request
*/ */
@ -473,7 +476,7 @@ export interface Interceptors {
/** /**
* Axios * Axios
*/ */
export interface Axios { export declare interface Axios {
/** /**
* *
*/ */
@ -571,14 +574,14 @@ export interface Axios {
/** /**
* Axios * Axios
*/ */
export interface AxiosConstructor { export declare interface AxiosConstructor {
new (config: AxiosRequestConfig): Axios; new (config: AxiosRequestConfig): Axios;
} }
/** /**
* AxiosError Error * AxiosError Error
*/ */
export interface AxiosError extends Error { export declare interface AxiosError extends Error {
/** /**
* Axios * Axios
*/ */
@ -603,7 +606,7 @@ export interface AxiosError extends Error {
/** /**
* *
*/ */
export interface Cancel { export declare interface Cancel {
/** /**
* *
*/ */
@ -618,28 +621,28 @@ export interface Cancel {
/** /**
* *
*/ */
export interface CancelConstructor { export declare interface CancelConstructor {
new (message?: string): Cancel; new (message?: string): Cancel;
} }
/** /**
* *
*/ */
export interface CancelAction { export declare interface CancelAction {
(message?: string): void; (message?: string): void;
} }
/** /**
* *
*/ */
export interface CancelExecutor { export declare interface CancelExecutor {
(cancel: CancelAction): void; (cancel: CancelAction): void;
} }
/** /**
* *
*/ */
export interface CancelToken { export declare interface CancelToken {
/** /**
* *
*/ */
@ -659,7 +662,7 @@ export interface CancelToken {
/** /**
* source * source
*/ */
export interface CancelTokenSource { export declare interface CancelTokenSource {
/** /**
* *
*/ */
@ -674,7 +677,7 @@ export interface CancelTokenSource {
/** /**
* *
*/ */
export interface CancelTokenConstructor { export declare interface CancelTokenConstructor {
new (executor: CancelExecutor): CancelToken; new (executor: CancelExecutor): CancelToken;
/** /**
@ -696,7 +699,7 @@ export interface CancelTokenConstructor {
* *
* * * *
*/ */
export interface AxiosBaseInstance extends Axios { export declare interface AxiosBaseInstance extends Axios {
/** /**
* *
* *
@ -720,7 +723,7 @@ export interface AxiosBaseInstance extends Axios {
* *
* * * *
*/ */
export interface AxiosInstance extends AxiosBaseInstance { export declare interface AxiosInstance extends AxiosBaseInstance {
/** /**
* Axios * Axios
* *
@ -744,4 +747,6 @@ export interface AxiosInstance extends AxiosBaseInstance {
* @param value * @param value
*/ */
isCancel: (value: any) => boolean; isCancel: (value: any) => boolean;
// extractData: <T extends Data>(response: Promise<AxiosResponse<T>>) => Promise<T>;
} }

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-20 20:47:09 * @Date: 2020-04-20 20:47:09
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-21 09:34:14 * @LastEditTime: 2020-04-22 16:04:16
*/ */
import Axios from '../../src/core/Axios'; import Axios from '../../src/core/Axios';

View File

@ -2,7 +2,7 @@
* @Author: early-autumn * @Author: early-autumn
* @Date: 2020-04-20 21:08:23 * @Date: 2020-04-20 21:08:23
* @LastEditors: early-autumn * @LastEditors: early-autumn
* @LastEditTime: 2020-04-20 21:17:31 * @LastEditTime: 2020-04-22 15:51:48
*/ */
import transformRequest from '../../src/core/transformRequest'; import transformRequest from '../../src/core/transformRequest';
@ -36,7 +36,7 @@ describe('测试 src/core/transformRequest.ts', () => {
const request2 = transformRequest({ const request2 = transformRequest({
baseURL: 'https://www.xxx.com', baseURL: 'https://www.xxx.com',
method: 'get', method: 'get',
url: 'https://www.yyy.com/test/', url: 'https://www.yyy.com/test',
params: { params: {
id: 1, id: 1,
}, },