From 5b442d95ce3dfe8f40709332a28f87fb2ee77d43 Mon Sep 17 00:00:00 2001 From: "954270063@qq.com" <954270063@qq.com> Date: Tue, 25 May 2021 23:17:29 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20utils=20?= =?UTF-8?q?=E4=B8=BA=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/axios.ts | 2 +- src/core/Axios.ts | 2 +- src/core/adapter.ts | 24 +++- src/core/dispatchRequest.ts | 2 +- src/core/flattenHeaders.ts | 3 +- src/core/generateType.ts | 3 +- src/core/mergeConfig.ts | 3 +- src/core/request.ts | 3 +- src/core/transformData.ts | 2 +- src/core/transformURL.ts | 2 +- src/helpers/is.ts | 41 +++++++ src/helpers/url.ts | 102 +++++++++++++++++ src/helpers/utils.ts | 54 +++++++++ src/utils.ts | 214 ------------------------------------ 14 files changed, 229 insertions(+), 228 deletions(-) create mode 100644 src/helpers/is.ts create mode 100644 src/helpers/url.ts create mode 100644 src/helpers/utils.ts delete mode 100644 src/utils.ts diff --git a/src/axios.ts b/src/axios.ts index 0b2345a..07d69a4 100644 --- a/src/axios.ts +++ b/src/axios.ts @@ -6,7 +6,7 @@ import Axios, { } from './core/Axios'; import { CancelToken, CancelTokenConstructor, isCancel } from './core/cancel'; import { mergeConfig } from './core/mergeConfig'; -import { isString } from './utils'; +import { isString } from './helpers/is'; import defaults from './defaults'; export interface AxiosInstance extends Axios { diff --git a/src/core/Axios.ts b/src/core/Axios.ts index 80e9985..c76c733 100644 --- a/src/core/Axios.ts +++ b/src/core/Axios.ts @@ -1,4 +1,4 @@ -import { buildURL } from '../utils'; +import { buildURL } from '../helpers/url'; import { mergeConfig } from './mergeConfig'; import { AdapterRequestMethod, diff --git a/src/core/adapter.ts b/src/core/adapter.ts index a908dfe..77551b8 100644 --- a/src/core/adapter.ts +++ b/src/core/adapter.ts @@ -1,13 +1,10 @@ import { - assert, isEmptyArray, isFunction, isPlainObject, - isPlatform, isUndefined, - revisePlatformApiNames, - throwError, -} from '../utils'; +} from '../helpers/is'; +import { assert, throwError } from '../helpers/utils'; import { AxiosProgressCallback, AxiosRequestConfig, @@ -86,6 +83,23 @@ export interface AxiosAdapter { (config: AxiosAdapterRequestConfig): AxiosAdapterTask | void; } +export function isPlatform(value: any): value is AxiosPlatform { + return ( + isPlainObject(value) && + isFunction(value.request) && + isFunction(value.upload) && + isFunction(value.download) + ); +} + +export function revisePlatformApiNames(platform: AnyObject): AxiosPlatform { + return { + request: platform.request ?? platform.httpRequest, + upload: platform.upload ?? platform.uploadFile, + download: platform.download ?? platform.downloadFile, + }; +} + export function createAdapter(platform: AxiosPlatform): AxiosAdapter { assert(isPlainObject(platform), 'platform 需要是一个 object'); assert(isFunction(platform.request), 'platform.request 需要是一个 function'); diff --git a/src/core/dispatchRequest.ts b/src/core/dispatchRequest.ts index 5baad47..b4bb0d3 100644 --- a/src/core/dispatchRequest.ts +++ b/src/core/dispatchRequest.ts @@ -1,4 +1,4 @@ -import { isPlainObject } from '../utils'; +import { isPlainObject } from '../helpers/is'; import { isCancel } from './cancel'; import { flattenHeaders } from './flattenHeaders'; import { transformData } from './transformData'; diff --git a/src/core/flattenHeaders.ts b/src/core/flattenHeaders.ts index 05aeb19..71db3c1 100644 --- a/src/core/flattenHeaders.ts +++ b/src/core/flattenHeaders.ts @@ -1,4 +1,5 @@ -import { isPlainObject, omit } from '../utils'; +import { isPlainObject } from '../helpers/is'; +import { omit } from '../helpers/utils'; import { AxiosRequestConfig, AxiosRequestMethodAlias, diff --git a/src/core/generateType.ts b/src/core/generateType.ts index 3837bbb..dbdb642 100644 --- a/src/core/generateType.ts +++ b/src/core/generateType.ts @@ -1,4 +1,5 @@ -import { assert, isPlainObject, isString } from '../utils'; +import { isPlainObject, isString } from 'src/helpers/is'; +import { assert } from '../helpers/utils'; import { AdapterRequestType } from './adapter'; import { AxiosRequestConfig } from './Axios'; diff --git a/src/core/mergeConfig.ts b/src/core/mergeConfig.ts index 7944976..ad73a92 100644 --- a/src/core/mergeConfig.ts +++ b/src/core/mergeConfig.ts @@ -1,4 +1,5 @@ -import { isPlainObject, deepMerge, isUndefined } from '../utils'; +import { isUndefined, isPlainObject } from '../helpers/is'; +import { deepMerge } from '../helpers/utils'; import { AxiosRequestConfig } from './Axios'; type AxiosRequestConfigKey = keyof AxiosRequestConfig; diff --git a/src/core/request.ts b/src/core/request.ts index cfdb5bc..27f1095 100644 --- a/src/core/request.ts +++ b/src/core/request.ts @@ -1,4 +1,5 @@ -import { assert, isFunction, isPlainObject } from '../utils'; +import { isFunction, isPlainObject } from '../helpers/is'; +import { assert } from '../helpers/utils'; import { AxiosAdapterRequestConfig, AdapterRequestMethod, diff --git a/src/core/transformData.ts b/src/core/transformData.ts index 19e39f6..cd8d84e 100644 --- a/src/core/transformData.ts +++ b/src/core/transformData.ts @@ -1,4 +1,4 @@ -import { isArray, isUndefined } from '../utils'; +import { isArray, isUndefined } from '../helpers/is'; import { AxiosRequestData, AxiosRequestFormData, diff --git a/src/core/transformURL.ts b/src/core/transformURL.ts index c98676c..0354846 100644 --- a/src/core/transformURL.ts +++ b/src/core/transformURL.ts @@ -4,7 +4,7 @@ import { dynamicInterpolation, isAbsoluteURL, isDynamicURL, -} from '../utils'; +} from '../helpers/url'; import { AxiosRequestConfig } from './Axios'; export function transformURL(config: AxiosRequestConfig): string { diff --git a/src/helpers/is.ts b/src/helpers/is.ts new file mode 100644 index 0000000..e81a91e --- /dev/null +++ b/src/helpers/is.ts @@ -0,0 +1,41 @@ +const _toString = Object.prototype.toString; + +export function isDate(date: any): date is Date { + return _toString.call(date) === '[object Date]'; +} + +export function isPlainObject( + value: any, +): value is [T] extends never[] ? AnyObject : T { + return _toString.call(value) === '[object Object]'; +} + +export function isUndefined(value: any): value is undefined { + return typeof value === 'undefined'; +} + +export function isString(value: any): value is string { + return typeof value === 'string'; +} + +export function isNull(value: any): value is null { + return value === null; +} + +export function isFunction( + value: any, +): value is T { + return typeof value === 'function'; +} + +export function isArray(value: any): value is T[] { + return Array.isArray(value); +} + +export function isEmptyArray(value: any): value is [] { + return isArray(value) && value.length === 0; +} + +export function isEmptyObject(value: any): value is {} { + return isPlainObject(value) && Object.keys(value).length === 0; +} diff --git a/src/helpers/url.ts b/src/helpers/url.ts new file mode 100644 index 0000000..80cbe62 --- /dev/null +++ b/src/helpers/url.ts @@ -0,0 +1,102 @@ +import { isDate, isNull, isPlainObject, isUndefined } from './is'; + +function encode(str: string): string { + return encodeURIComponent(str) + .replace(/%40/gi, '@') + .replace(/%3A/gi, ':') + .replace(/%24/g, '$') + .replace(/%2C/gi, ',') + .replace(/%20/g, '+') + .replace(/%5B/gi, '[') + .replace(/%5D/gi, ']'); +} + +function generateURL(url: string, serializedParams: string): string { + const hashIndex = url.indexOf('#'); + + if (hashIndex !== -1) { + url = url.slice(0, hashIndex); + } + + if (serializedParams === '') { + return url; + } + + const prefix = url.indexOf('?') === -1 ? '?' : '&'; + + serializedParams = `${prefix}${serializedParams}`; + + return `${url}${serializedParams}`; +} + +function paramsSerialization(params?: any): string { + if (!isPlainObject(params)) { + return ''; + } + + const parts: string[] = []; + + Object.keys(params).forEach((key): void => { + const value = params[key]; + + if (isNull(value) || isUndefined(value) || value !== value) { + return; + } + + if (Array.isArray(value)) { + key += '[]'; + } + + const values = [].concat(value); + + values.forEach((val: any): void => { + if (isPlainObject(val)) { + val = JSON.stringify(val); + } else if (isDate(val)) { + val = (val as Date).toISOString(); + } + + parts.push(`${encode(key)}=${encode(val)}`); + }); + }); + + return parts.join('&'); +} + +export function buildURL( + url = '', + params?: any, + paramsSerializer = paramsSerialization, +): string { + if (!isPlainObject(params)) { + return url; + } + + return generateURL(url, paramsSerializer(params)); +} + +export const combineREG = /(? + key1.replace(key2, sourceData[key3]), + ); +} + +export const absoluteREG = /^([a-z][a-z\d+\-.]*:)?\/\//i; +export function isAbsoluteURL(url: string): boolean { + return absoluteREG.test(url); +} diff --git a/src/helpers/utils.ts b/src/helpers/utils.ts new file mode 100644 index 0000000..6854f1c --- /dev/null +++ b/src/helpers/utils.ts @@ -0,0 +1,54 @@ +import { isPlainObject } from './is'; + +export function deepMerge(...objs: T[]): T { + const result: AnyObject = {}; + + objs.forEach((obj: AnyObject) => + Object.keys(obj).forEach((key) => { + const val = obj[key]; + const resultVal = result[key]; + + if (isPlainObject(resultVal) && isPlainObject(val)) { + result[key] = deepMerge(resultVal, val); + } else if (isPlainObject(val)) { + result[key] = deepMerge(val); + } else { + result[key] = val; + } + }), + ); + + return result as T; +} + +export function pick( + obj: T, + ...keys: K[] +): Pick { + const _pick: Partial = {}; + + keys.forEach((key: K) => (_pick[key] = obj[key])); + + return _pick as Pick; +} + +export function omit( + obj: T, + ...keys: K[] +): Omit { + const _omit = Object.assign({}, obj); + + keys.forEach((key: K) => delete _omit[key]); + + return _omit; +} + +export function assert(condition: boolean, msg: string) { + if (!condition) { + throwError(msg); + } +} + +export function throwError(msg: string): void { + throw new Error(`[axios-miniprogram]:${msg}`); +} diff --git a/src/utils.ts b/src/utils.ts deleted file mode 100644 index 417a617..0000000 --- a/src/utils.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { AxiosPlatform } from './core/adapter'; -import { AxiosRequestData, AxiosRequestParams } from './core/Axios'; - -const _toString = Object.prototype.toString; - -export function isDate(date: any): date is Date { - return _toString.call(date) === '[object Date]'; -} - -export function isPlainObject( - value: any, -): value is [T] extends never[] ? AnyObject : T { - return _toString.call(value) === '[object Object]'; -} - -export function isUndefined(value: any): value is undefined { - return typeof value === 'undefined'; -} - -export function isString(value: any): value is string { - return typeof value === 'string'; -} - -export function isNull(value: any): value is null { - return value === null; -} - -export function isFunction( - value: any, -): value is T { - return typeof value === 'function'; -} - -export function isArray(value: any): value is T[] { - return Array.isArray(value); -} - -export function isEmptyArray(value: any): value is [] { - return isArray(value) && value.length === 0; -} - -export function isPlatform(value: any): value is AxiosPlatform { - return ( - isPlainObject(value) && - isFunction(value.request) && - isFunction(value.upload) && - isFunction(value.download) - ); -} - -export function deepMerge(...objs: T[]): T { - const result: AnyObject = {}; - - objs.forEach((obj: AnyObject) => - Object.keys(obj).forEach((key) => { - const val = obj[key]; - const resultVal = result[key]; - - if (isPlainObject(resultVal) && isPlainObject(val)) { - result[key] = deepMerge(resultVal, val); - } else if (isPlainObject(val)) { - result[key] = deepMerge(val); - } else { - result[key] = val; - } - }), - ); - - return result as T; -} - -export function pick( - obj: T, - ...keys: K[] -): Pick { - const _pick: Partial = {}; - - keys.forEach((key: K) => (_pick[key] = obj[key])); - - return _pick as Pick; -} - -export function omit( - obj: T, - ...keys: K[] -): Omit { - const _omit = Object.assign({}, obj); - - keys.forEach((key: K) => delete _omit[key]); - - return _omit; -} - -export function revisePlatformApiNames(platform: AnyObject): AxiosPlatform { - return { - request: platform.request ?? platform.httpRequest, - upload: platform.upload ?? platform.uploadFile, - download: platform.download ?? platform.downloadFile, - }; -} - -export function assert(condition: boolean, msg: string) { - if (!condition) { - throwError(msg); - } -} - -export function throwError(msg: string): void { - throw new Error(`[axios-miniprogram]:${msg}`); -} - -function encode(str: string): string { - return encodeURIComponent(str) - .replace(/%40/gi, '@') - .replace(/%3A/gi, ':') - .replace(/%24/g, '$') - .replace(/%2C/gi, ',') - .replace(/%20/g, '+') - .replace(/%5B/gi, '[') - .replace(/%5D/gi, ']'); -} - -function generateURL(url: string, serializedParams: string): string { - const hashIndex = url.indexOf('#'); - - if (hashIndex !== -1) { - url = url.slice(0, hashIndex); - } - - if (serializedParams === '') { - return url; - } - - const prefix = url.indexOf('?') === -1 ? '?' : '&'; - - serializedParams = `${prefix}${serializedParams}`; - - return `${url}${serializedParams}`; -} - -function paramsSerialization(params?: AxiosRequestParams): string { - if (!isPlainObject(params)) { - return ''; - } - - const parts: string[] = []; - - Object.keys(params).forEach((key): void => { - const value = params[key]; - - if (isNull(value) || isUndefined(value) || value !== value) { - return; - } - - if (Array.isArray(value)) { - key += '[]'; - } - - const values = [].concat(value); - - values.forEach((val: any): void => { - if (isPlainObject(val)) { - val = JSON.stringify(val); - } else if (isDate(val)) { - val = val.toISOString(); - } - - parts.push(`${encode(key)}=${encode(val)}`); - }); - }); - - return parts.join('&'); -} - -export function buildURL( - url = '', - params?: AxiosRequestParams, - paramsSerializer = paramsSerialization, -): string { - if (!isPlainObject(params)) { - return url; - } - - return generateURL(url, paramsSerializer(params)); -} - -export const combineREG = /(? - key1.replace(key2, sourceData[key3]), - ); -} - -export const absoluteREG = /^([a-z][a-z\d+\-.]*:)?\/\//i; -export function isAbsoluteURL(url: string): boolean { - return absoluteREG.test(url); -}