push
This commit is contained in:
59
lib/use/use-api.ts
Normal file
59
lib/use/use-api.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { AxiosRequestConfig } from 'axios';
|
||||
import { http } from '../util/http';
|
||||
import { isFunction, isPlainObject, isString } from 'lodash-es';
|
||||
import { usePath } from '/nerv-lib/use/use-path';
|
||||
export type HttpRequestConfig = AxiosRequestConfig;
|
||||
|
||||
export interface HttpRequest {
|
||||
api: string | HttpRequestConfig | Function;
|
||||
pathParams?: Recordable; // 获取动态路径
|
||||
params?: Recordable;
|
||||
paramsFilter?: Function;
|
||||
requestConfig?: HttpRequestConfig;
|
||||
}
|
||||
|
||||
export function useApi() {
|
||||
const { getPath } = usePath();
|
||||
|
||||
function httpRequest({
|
||||
api,
|
||||
params = {},
|
||||
pathParams,
|
||||
paramsFilter,
|
||||
requestConfig = {},
|
||||
}: HttpRequest) {
|
||||
if (!pathParams) {
|
||||
pathParams = params;
|
||||
}
|
||||
|
||||
let url = undefined;
|
||||
if (isString(api)) {
|
||||
url = getPath(api, pathParams);
|
||||
} else if (isPlainObject(api)) {
|
||||
requestConfig = Object.assign(requestConfig, api);
|
||||
console.log('rrrrr', requestConfig);
|
||||
if (requestConfig?.url) {
|
||||
url = getPath(requestConfig.url, pathParams);
|
||||
}
|
||||
}
|
||||
if (paramsFilter) {
|
||||
params = paramsFilter(params);
|
||||
}
|
||||
|
||||
if (requestConfig?.method?.toLocaleLowerCase() === 'get') {
|
||||
if (!requestConfig.params) requestConfig.params = params;
|
||||
} else {
|
||||
if (!requestConfig.data) requestConfig.data = params;
|
||||
}
|
||||
|
||||
if (isFunction(api)) {
|
||||
return api(params);
|
||||
} else {
|
||||
return http.request({
|
||||
...requestConfig,
|
||||
url,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { httpRequest };
|
||||
}
|
||||
Reference in New Issue
Block a user