refactor: Request使用依赖 @luch-request

This commit is contained in:
Huang 2022-09-14 15:33:40 +08:00
parent 28a7ec0dc2
commit b1ec2157d7
16 changed files with 16 additions and 802 deletions

View File

@ -51,6 +51,7 @@
"crypto-js": "^4.1.1", "crypto-js": "^4.1.1",
"echarts": "^5.3.3", "echarts": "^5.3.3",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"luch-request": "^3.0.8",
"pinia": "^2.0.22", "pinia": "^2.0.22",
"vue": "^3.2.39", "vue": "^3.2.39",
"vue-i18n": "^9.2.2" "vue-i18n": "^9.2.2"

11
pnpm-lock.yaml generated
View File

@ -33,6 +33,7 @@ specifiers:
husky: ^8.0.1 husky: ^8.0.1
lint-staged: ^13.0.3 lint-staged: ^13.0.3
lodash-es: ^4.17.21 lodash-es: ^4.17.21
luch-request: ^3.0.8
mrm: ^4.1.0 mrm: ^4.1.0
pinia: ^2.0.22 pinia: ^2.0.22
postcss: ^8.4.16 postcss: ^8.4.16
@ -63,6 +64,7 @@ dependencies:
crypto-js: registry.npmmirror.com/crypto-js/4.1.1 crypto-js: registry.npmmirror.com/crypto-js/4.1.1
echarts: registry.npmmirror.com/echarts/5.3.3 echarts: registry.npmmirror.com/echarts/5.3.3
lodash-es: registry.npmmirror.com/lodash-es/4.17.21 lodash-es: registry.npmmirror.com/lodash-es/4.17.21
luch-request: registry.npmmirror.com/luch-request/3.0.8
pinia: registry.npmmirror.com/pinia/2.0.22_arz4dztosvwy2ghjrlh2wdhejm pinia: registry.npmmirror.com/pinia/2.0.22_arz4dztosvwy2ghjrlh2wdhejm
vue: registry.npmmirror.com/vue/3.2.39 vue: registry.npmmirror.com/vue/3.2.39
vue-i18n: registry.npmmirror.com/vue-i18n/9.2.2_vue@3.2.39 vue-i18n: registry.npmmirror.com/vue-i18n/9.2.2_vue@3.2.39
@ -462,7 +464,6 @@ packages:
resolution: {integrity: sha512-mrCMwcINy1IFjU9VUqLeWBkj404yWs5paLDttBcA+eqUjanuUQbBcTVPqlrGgkyzLXDcV2oDDZRSNxNpXi4kMQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/@dcloudio/types/-/types-2.6.12.tgz} resolution: {integrity: sha512-mrCMwcINy1IFjU9VUqLeWBkj404yWs5paLDttBcA+eqUjanuUQbBcTVPqlrGgkyzLXDcV2oDDZRSNxNpXi4kMQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/@dcloudio/types/-/types-2.6.12.tgz}
name: '@dcloudio/types' name: '@dcloudio/types'
version: 2.6.12 version: 2.6.12
dev: true
registry.npmmirror.com/@dcloudio/uni-app-plus/3.0.0-alpha-3060120220907003_6ehzcaeklggzprjid7wmf2r2bu: registry.npmmirror.com/@dcloudio/uni-app-plus/3.0.0-alpha-3060120220907003_6ehzcaeklggzprjid7wmf2r2bu:
resolution: {integrity: sha512-/WNKSivCEP75V+/nenL2hrL5Hb9RmMR8EtT8DW1Qki5YvcSBTu1uoJM5x/xYV/hZ+ZHHPdLrfqCT5AIpJoNt7Q==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/@dcloudio/uni-app-plus/-/uni-app-plus-3.0.0-alpha-3060120220907003.tgz} resolution: {integrity: sha512-/WNKSivCEP75V+/nenL2hrL5Hb9RmMR8EtT8DW1Qki5YvcSBTu1uoJM5x/xYV/hZ+ZHHPdLrfqCT5AIpJoNt7Q==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/@dcloudio/uni-app-plus/-/uni-app-plus-3.0.0-alpha-3060120220907003.tgz}
@ -4800,6 +4801,14 @@ packages:
yallist: registry.npmmirror.com/yallist/4.0.0 yallist: registry.npmmirror.com/yallist/4.0.0
dev: true dev: true
registry.npmmirror.com/luch-request/3.0.8:
resolution: {integrity: sha512-5ZVp1y4tFaizbGMOuQwbeyfHnf4PhQAwQ3S1Fm1tS7juMoB14pXslxWriElhiSq6ytYYW0KVC8RShfHiNujFcQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/luch-request/-/luch-request-3.0.8.tgz}
name: luch-request
version: 3.0.8
dependencies:
'@dcloudio/types': registry.npmmirror.com/@dcloudio/types/2.6.12
dev: false
registry.npmmirror.com/magic-string/0.25.9: registry.npmmirror.com/magic-string/0.25.9:
resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/magic-string/-/magic-string-0.25.9.tgz} resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==, registry: https://registry.npm.taobao.org/, tarball: https://registry.npmmirror.com/magic-string/-/magic-string-0.25.9.tgz}
name: magic-string name: magic-string

View File

@ -1,133 +0,0 @@
import buildURL from '../helpers/buildURL';
import buildFullPath from '../core/buildFullPath';
import settle from '../core/settle';
import { isUndefined } from '../utils';
import { HttpRequestConfig, HttpResponse } from '@/types/http';
import { cloneDeep } from 'lodash-es';
/**
*
* @param {Array} keys -
* @param {Object} config2 -
* @return {{}} -
*/
const mergeKeys = (keys: string[], config2: Record<string, any>) => {
const config: Record<string, any> = {};
keys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop];
}
});
return config;
};
export default <T>(config: HttpRequestConfig) => {
return new Promise<T>((resolve, reject) => {
const fullPath = buildURL(buildFullPath(config.baseURL, config.url || ''), config.params);
const _config: UniApp.RequestOptions = {
url: fullPath,
header: config.header,
success: (res) => {
try {
// 对可能字符串不是json 的情况容错
if (typeof res.data === 'string') {
res.data = JSON.parse(res.data);
}
} catch (e: any) {
reject(e);
}
const cloneConfig = cloneDeep(config);
cloneConfig.fullPath = fullPath;
const response = {
...res,
config: cloneConfig,
} as HttpResponse;
settle(resolve, reject, response);
},
fail: (err) => {
const cloneConfig = cloneDeep(config);
cloneConfig.fullPath = fullPath;
const response = {
...err,
config: cloneConfig,
} as HttpResponse;
settle(resolve, reject, response);
},
// complete: (response) => {
// config.fullPath = fullPath;
// response.config = config;
// try {
// // 对可能字符串不是json 的情况容错
// if (typeof response.data === 'string') {
// response.data = JSON.parse(response.data);
// }
// // eslint-disable-next-line no-empty
// } catch (e) {}
// settle(resolve, reject, response);
// },
};
let requestTask;
if (config.method === 'UPLOAD') {
delete _config.header['content-type'];
delete _config.header['Content-Type'];
const otherConfig = {
// #ifdef MP-ALIPAY
fileType: config.fileType,
// #endif
filePath: config.filePath,
name: config.name,
};
const optionalKeys = [
// #ifdef APP-PLUS || H5
'files',
// #endif
// #ifdef H5
'file',
// #endif
// #ifdef H5 || APP-PLUS
'timeout',
// #endif
'formData',
];
const uploadFileOption = {
..._config,
...otherConfig,
...mergeKeys(optionalKeys, config),
} as UniApp.UploadFileOption;
requestTask = uni.uploadFile(uploadFileOption);
} else if (config.method === 'DOWNLOAD') {
// #ifdef H5 || APP-PLUS
if (!isUndefined(config['timeout'])) {
_config['timeout'] = config['timeout'];
}
// #endif
const downloadFileOption = _config as UniApp.DownloadFileOption;
requestTask = uni.downloadFile(downloadFileOption);
} else {
const optionalKeys = [
'data',
'method',
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
'timeout',
// #endif
'dataType',
// #ifndef MP-ALIPAY
'responseType',
// #endif
// #ifdef APP-PLUS
'sslVerify',
// #endif
// #ifdef H5
'withCredentials',
// #endif
// #ifdef APP-PLUS
'firstIpv4',
// #endif
];
requestTask = uni.request({ ..._config, ...mergeKeys(optionalKeys, config) });
}
if (config.getTask) {
config.getTask(requestTask, config);
}
});
};

View File

@ -1,49 +0,0 @@
function InterceptorManager(): void {
// @ts-ignore
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled: any, rejected: any) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id: number) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn: (h: any) => void) {
this.handlers.forEach((h: any) => {
if (h !== null) {
fn(h);
}
});
};
export default InterceptorManager;

View File

@ -1,202 +0,0 @@
/**
* @Class Request
* @description luch-request http请求插件
* @version 3.0.7
* @Author lu-ch
* @Date 2021-09-04
* @Email webwork.s@qq.com
* 文档: https://www.quanzhan.co/luch-request/
* github: https://github.com/lei-mu/luch-request
* DCloud: http://ext.dcloud.net.cn/plugin?id=392
* HBuilderX: beat-3.0.4 alpha-3.0.4
* 2022-06-09 ts
*/
import dispatchRequest from './dispatchRequest';
import InterceptorManager from './InterceptorManager';
import mergeConfig from './mergeConfig';
import defaults from './defaults';
import { cloneDeep } from 'lodash-es';
import { isPlainObject } from '../utils';
import { HttpRequestConfig, HttpResponse, Interceptors } from '@/types/http';
export default class Request {
private config: HttpRequestConfig;
interceptors: Interceptors;
/**
* @param {Object} arg -
* @param {String} arg.baseURL -
* @param {Object} arg.header - header
* @param {String} arg.method = [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE] -
* @param {String} arg.dataType = [json] - dataType
* @param {String} arg.responseType = [text|arraybuffer] - responseType
* @param {Object} arg.custom -
* @param {Number} arg.timeout - ms60000H5(HBuilderX 2.9.9+)APP(HBuilderX 2.9.9+)2.10.0
* @param {Boolean} arg.sslVerify - ssl true.App安卓端支持HBuilderX 2.3.3+
* @param {Boolean} arg.withCredentials - cookiesfalseH5支持HBuilderX 2.6.15+
* @param {Boolean} arg.firstIpv4 - DNS解析时优先使用ipv4false App-Android (HBuilderX 2.8.0+)
* @param {Function(statusCode):Boolean} arg.validateStatus - statusCode >= 200 && statusCode < 300
*/
constructor(arg?: Partial<HttpRequestConfig>) {
if (!isPlainObject(arg)) {
arg = {};
console.warn('设置全局参数必须接收一个Object');
}
this.config = cloneDeep({ ...defaults, ...arg });
this.interceptors = {
// @ts-ignore
request: new InterceptorManager(),
// @ts-ignore
response: new InterceptorManager(),
};
}
/**
* @Function
* @param {Request~setConfigCallback} f -
*/
setConfig(f: (_config: HttpRequestConfig) => HttpRequestConfig) {
this.config = f(this.config);
}
middleware<T>(config: HttpRequestConfig) {
config = mergeConfig(this.config, config);
const chain = [dispatchRequest, undefined];
const response: HttpResponse<T> = {
config: config,
} as HttpResponse<T>;
let promise = Promise.resolve(response);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor: any) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor: any) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then<HttpResponse<T>>(chain.shift(), chain.shift());
}
return promise;
}
/**
* @Function
* @param {Object} config -
* @prop {String} options.url -
* @prop {Object} options.data -
* @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] -
* @prop {Object} [options.dataType = config.dataType] - json JSON.parse
* @prop {Object} [options.header = config.header] - header
* @prop {Object} [options.method = config.method] -
* @returns {Promise<unknown>}
*/
request<T>(config: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>(config);
}
get<T>(url: string, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
method: 'GET',
...options,
});
}
post<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'POST',
...options,
});
}
// #ifndef MP-ALIPAY
put<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'PUT',
...options,
});
}
// #endif
// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
delete<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'DELETE',
...options,
});
}
// #endif
// #ifdef H5 || MP-WEIXIN
connect<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'CONNECT',
...options,
});
}
// #endif
// #ifdef H5 || MP-WEIXIN || MP-BAIDU
head<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'HEAD',
...options,
});
}
// #endif
// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
options<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'OPTIONS',
...options,
});
}
// #endif
// #ifdef H5 || MP-WEIXIN
trace<T>(url: string, data: AnyObject, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
data,
method: 'TRACE',
...options,
});
}
// #endif
upload<T>(url: string, config: Partial<HttpRequestConfig> = {}) {
config.url = url;
config.method = 'UPLOAD';
return this.middleware<T>(config);
}
download<T>(url: string, config: Partial<HttpRequestConfig> = {}) {
config.url = url;
config.method = 'DOWNLOAD';
return this.middleware<T>(config);
}
}
/**
* setConfig回调
* @return {Object} - config
* @callback Request~setConfigCallback
* @param {Object} config - config
*/

View File

@ -1,18 +0,0 @@
import isAbsoluteURL from '../helpers/isAbsoluteURL';
import combineURLs from '../helpers/combineURLs';
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
export default function buildFullPath(baseURL: string | undefined, requestedURL: string): string {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}

View File

@ -1,31 +0,0 @@
import { HttpRequestConfig } from '@/types/http';
/**
*
*/
export default {
baseURL: '',
header: {},
method: 'GET',
dataType: 'json',
// #ifndef MP-ALIPAY
responseType: 'text',
// #endif
custom: {},
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
timeout: 60000,
// #endif
// #ifdef APP-PLUS
sslVerify: true,
// #endif
// #ifdef H5
withCredentials: false,
// #endif
// #ifdef APP-PLUS
firstIpv4: false,
// #endif
validateStatus: function validateStatus(status: number) {
return status >= 200 && status < 300;
},
} as HttpRequestConfig;

View File

@ -1,6 +0,0 @@
import adapter from '../adapters';
import { HttpRequestConfig } from '@/types/http';
export default <T>(config: HttpRequestConfig) => {
return adapter<T>(config.config);
};

View File

@ -1,111 +0,0 @@
import { deepMerge, isUndefined } from '../utils';
import { HttpRequestConfig } from '@/types/http';
/**
*
* @param {Array} keys -
* @param {Object} globalsConfig -
* @param {Object} config2 -
* @return {{}}
*/
const mergeKeys = (
keys: string[],
globalsConfig: HttpRequestConfig,
config2: Partial<HttpRequestConfig>,
) => {
const config: Partial<HttpRequestConfig> = {};
keys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop];
} else if (!isUndefined(globalsConfig[prop])) {
config[prop] = globalsConfig[prop];
}
});
return config;
};
/**
*
* @param globalsConfig -
* @param config2 -
* @return -
*/
export default (globalsConfig: HttpRequestConfig, config2: Partial<HttpRequestConfig> = {}) => {
const method = config2.method || globalsConfig.method || 'GET';
let config: Partial<HttpRequestConfig> = {
baseURL: globalsConfig.baseURL || '',
method: method,
url: config2.url || '',
params: config2.params || {},
custom: { ...(globalsConfig.custom || {}), ...(config2.custom || {}) },
// @ts-ignore
header: deepMerge(globalsConfig.header || {}, config2.header || {}),
};
const defaultToConfig2Keys = ['getTask', 'validateStatus'];
config = { ...config, ...mergeKeys(defaultToConfig2Keys, globalsConfig, config2) };
// eslint-disable-next-line no-empty
if (method === 'DOWNLOAD') {
// #ifdef H5 || APP-PLUS
if (!isUndefined(config2.timeout)) {
config['timeout'] = config2['timeout'];
} else if (!isUndefined(globalsConfig.timeout)) {
config['timeout'] = globalsConfig['timeout'];
}
// #endif
} else if (method === 'UPLOAD') {
if (config.header) {
delete config.header['content-type'];
delete config.header['Content-Type'];
}
const uploadKeys = [
// #ifdef APP-PLUS || H5
'files',
// #endif
// #ifdef MP-ALIPAY
'fileType',
// #endif
// #ifdef H5
'file',
// #endif
'filePath',
'name',
// #ifdef H5 || APP-PLUS
'timeout',
// #endif
'formData',
];
uploadKeys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop];
}
});
// #ifdef H5 || APP-PLUS
if (isUndefined(config.timeout) && !isUndefined(globalsConfig.timeout)) {
config['timeout'] = globalsConfig['timeout'];
}
// #endif
} else {
const defaultsKeys = [
'data',
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
'timeout',
// #endif
'dataType',
// #ifndef MP-ALIPAY
'responseType',
// #endif
// #ifdef APP-PLUS
'sslVerify',
// #endif
// #ifdef H5
'withCredentials',
// #endif
// #ifdef APP-PLUS
'firstIpv4',
// #endif
];
config = { ...config, ...mergeKeys(defaultsKeys, globalsConfig, config2) };
}
return config;
};

View File

@ -1,18 +0,0 @@
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
import { HttpResponse } from '@/types/http';
export default function settle(resolve: any, reject: any, response: HttpResponse) {
const validateStatus = response.config.validateStatus;
const status = response.statusCode;
if (status && (!validateStatus || validateStatus(status))) {
resolve(response);
} else {
reject(response);
}
}

View File

@ -1,66 +0,0 @@
import * as utils from '../utils';
function encode(val: string | number | boolean) {
return encodeURIComponent(val)
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+')
.replace(/%5B/gi, '[')
.replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
export default function buildURL(url: string, params?: any) {
if (!params) {
return url;
}
let serializedParams;
if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
const parts: string[] = [];
utils.forEach(params, function serialize(val: any, key: string) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v: any) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}

View File

@ -1,12 +0,0 @@
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
export default function combineURLs(baseURL: string, relativeURL: string): string {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}

View File

@ -1,12 +0,0 @@
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
export default function isAbsoluteURL(url: string): boolean {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}

View File

@ -1,4 +1,4 @@
import Request from './core/Request'; import Request from 'luch-request';
import { assign } from 'lodash-es'; import { assign } from 'lodash-es';
import { HttpSuccess } from '@/types/http'; import { HttpSuccess } from '@/types/http';
import { Toast } from '@/utils/uniapi/prompt'; import { Toast } from '@/utils/uniapi/prompt';
@ -28,15 +28,14 @@ const request = createRequest();
*/ */
request.interceptors.request.use( request.interceptors.request.use(
(options) => { (options) => {
const { config } = options; if (options.custom?.auth) {
if (config.custom?.auth) {
const authStore = useAuthStore(); const authStore = useAuthStore();
if (!authStore.isLogin) { if (!authStore.isLogin) {
Toast('请先登录'); Toast('请先登录');
// token不存在跳转到登录页 // token不存在跳转到登录页
return Promise.reject(options); return Promise.reject(options);
} }
config.header = assign(config.header, { options.header = assign(options.header, {
authorization: `Bearer ${authStore.getToken}`, authorization: `Bearer ${authStore.getToken}`,
}); });
} }

View File

@ -1,136 +0,0 @@
// utils is a library of generic helper functions non-specific to axios
const toString = Object.prototype.toString;
export function is(val: unknown, type: string) {
return toString.call(val) === `[object ${type}]`;
}
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
export function isArray(val: any): val is Array<any> {
return val && Array.isArray(val);
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
export function isObject(val: any): val is Record<any, any> {
return val !== null && is(val, 'Object');
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
export function isDate(val: unknown): val is Date {
return is(val, 'Date');
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
export function isURLSearchParams(val: unknown): val is URLSearchParams {
return is(val, 'URLSearchParams');
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
export function forEach(obj: any, fn: any) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
obj.forEach((val, index, curObj) => {
fn.call(null, val, index, curObj);
});
} else {
// Iterate over object keys
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* boolean
* @param val
* @returns {boolean}
*/
export function isBoolean(val: unknown): val is boolean {
return is(val, 'Boolean');
}
/**
* {} new Object
* @param {any} obj -
* @returns {boolean}
*/
export function isPlainObject(obj: unknown): boolean {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
export function deepMerge(/* obj1, obj2, obj3, ... */) {
const result: any = {};
function assignValue(val: any, key: any) {
if (typeof result[key] === 'object' && typeof val === 'object') {
// @ts-ignore
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
// @ts-ignore
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (let i = 0, l = arguments.length; i < l; i++) {
// eslint-disable-next-line prefer-rest-params
forEach(arguments[i], assignValue);
}
return result;
}
export function isUndefined<T = unknown>(val?: T): val is T {
return typeof val === 'undefined';
}

View File

@ -10,7 +10,7 @@
"resolveJsonModule": true, "resolveJsonModule": true,
"esModuleInterop": true, "esModuleInterop": true,
"lib": ["esnext", "dom"], "lib": ["esnext", "dom"],
"types": ["@dcloudio/types","src/tmui/interface.ts"], "types": ["@dcloudio/types"],
"paths": { "paths": {
"@/*":["./src/*"] "@/*":["./src/*"]
} }
@ -19,7 +19,6 @@
"src/**/*.ts", "src/**/*.ts",
"src/**/*.d.ts", "src/**/*.d.ts",
"src/**/*.tsx", "src/**/*.tsx",
"src/**/*.vue", "src/**/*.vue"
"node_modules/@dcloudio/types/uni-app/uni.d.ts",
] ]
} }