gtsoft-snail-job-admin/packages/hooks/src/use-request.ts

80 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-03-08 17:59:45 +08:00
import { ref } from 'vue';
import type { Ref } from 'vue';
import { createFlatRequest } from '@sa/axios';
import type {
AxiosError,
CreateAxiosDefaults,
CustomAxiosRequestConfig,
MappedType,
RequestOption,
ResponseType
} from '@sa/axios';
import useLoading from './use-loading';
export type HookRequestInstanceResponseSuccessData<T = any> = {
data: Ref<T>;
error: Ref<null>;
};
2024-04-10 11:25:25 +08:00
export type HookRequestInstanceResponseFailData<ResponseData = any> = {
2024-03-08 17:59:45 +08:00
data: Ref<null>;
2024-04-10 11:25:25 +08:00
error: Ref<AxiosError<ResponseData>>;
2024-03-08 17:59:45 +08:00
};
2024-04-10 11:25:25 +08:00
export type HookRequestInstanceResponseData<T = any, ResponseData = any> = {
2024-03-08 17:59:45 +08:00
loading: Ref<boolean>;
2024-04-10 11:25:25 +08:00
} & (HookRequestInstanceResponseSuccessData<T> | HookRequestInstanceResponseFailData<ResponseData>);
2024-03-08 17:59:45 +08:00
2024-04-10 11:25:25 +08:00
export interface HookRequestInstance<ResponseData = any> {
2024-03-08 17:59:45 +08:00
<T = any, R extends ResponseType = 'json'>(
config: CustomAxiosRequestConfig
2024-04-10 11:25:25 +08:00
): HookRequestInstanceResponseData<MappedType<R, T>, ResponseData>;
2024-03-08 17:59:45 +08:00
cancelRequest: (requestId: string) => void;
cancelAllRequest: () => void;
}
/**
* create a hook request instance
*
* @param axiosConfig
* @param options
*/
export default function createHookRequest<ResponseData = any>(
axiosConfig?: CreateAxiosDefaults,
options?: Partial<RequestOption<ResponseData>>
) {
const request = createFlatRequest<ResponseData>(axiosConfig, options);
2024-04-10 11:25:25 +08:00
const hookRequest: HookRequestInstance<ResponseData> = function hookRequest<T = any, R extends ResponseType = 'json'>(
2024-03-08 17:59:45 +08:00
config: CustomAxiosRequestConfig
) {
const { loading, startLoading, endLoading } = useLoading();
2024-04-10 11:25:25 +08:00
const data = ref<MappedType<R, T> | null>(null) as Ref<MappedType<R, T>>;
const error = ref<AxiosError<ResponseData> | null>(null) as Ref<AxiosError<ResponseData> | null>;
2024-03-08 17:59:45 +08:00
startLoading();
request(config).then(res => {
if (res.data) {
data.value = res.data;
} else {
error.value = res.error;
}
endLoading();
});
return {
loading,
data,
error
};
2024-04-10 11:25:25 +08:00
} as HookRequestInstance<ResponseData>;
2024-03-08 17:59:45 +08:00
hookRequest.cancelRequest = request.cancelRequest;
hookRequest.cancelAllRequest = request.cancelAllRequest;
return hookRequest;
}