You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB

4 months ago
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';
import { RequestEnum } from '/@/enum/http-enum.ts';
4 months ago
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 (RequestEnum[requestConfig?.method?.toLocaleUpperCase()] === 'GET') {
4 months ago
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 };
}