Unverified Commit 1d3add65 authored by gaoyan's avatar gaoyan Committed by GitHub

Add use hook (#2577)

* Optimize the process * add request hook * add request hook * add request hook * formate code * delete useService * fix import * fix code style * fix code style
parent cb88b63a
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { ErrorNotification, SuccessMessage } from '@/utils/messages';
import { RequestConfig, useRequest } from '@umijs/max';
import { useCallback } from 'react';
const noop = () => {};
/**
* return CRUDResult type
*/
interface CRUDResult<T> {
data: T | undefined; // 表示请求返回的数据。
error: Error | undefined; // 表示请求返回的错误。
loading: boolean; // 表示请求是否正在进行中。
params: any; // 表示请求参数。
run: (config?: RequestConfig) => Promise<any>; // 可以手动触发请求。
cancel: () => void; // 用于取消当前请求。
refresh: () => Promise<any>; // 用于重新发起请求
mutate: (newData: T | undefined) => void; // 用于手动更新数据
addData: (payload: any) => Promise<any>; // 用于创建新数据/更新数据。
getDataList: () => Promise<any>; // 用于读取数据。
updateData: (id: number, payload: any) => Promise<any>; // 用于更新数据。
removeDataById: (id: number) => Promise<any>; // 用于删除数据。
}
/**
* useCustomCRUD hook
* @param url 请求的url
* @param options 请求的配置
*/
const useCustomCRUD = (url: string, options = {}): CRUDResult<any> => {
/**
* @name BaseOptions
* @note
* refreshDeps?: DependencyList; // 当前请求的依赖项
* manual?: boolean; // 手动刷新
* onSuccess?: (data: R, params: P) => void; // 请求成功时的回调
* onError?: (e: Error, params: P) => void; // 请求失败时的回调
* defaultLoading?: boolean; //默认加载
* loadingDelay?: number; // 加载延迟
* defaultParams?: P; // 默认参数
* pollingInterval?: number; // 轮询间隔
* pollingWhenHidden?: boolean; // 隐藏时是否轮询
* fetchKey?: (...args: P) => string; // 请求key
* paginated?: false; // 分页
* loadMore?: false; // 加载更多
* refreshOnWindowFocus?: boolean; // 窗口获取焦点时是否刷新
* focusTimespan?: number; // 焦点时间跨度
* cacheKey?: CachedKeyType; // 缓存键
* cacheTime?: number; // 缓存时间
* staleTime?: number; // 缓存时间
* debounceInterval?: number; // 防抖间隔时间
* throttleInterval?: number; //
* initialData?: R; // 初始数据
* requestMethod?: (service: any) => Promise<any>; // 请求方法
* getDataListy?: boolean; // 初始化状态
* throwOnError?: boolean; // 抛出错误
*/
const { data, error, loading, params, run, cancel, refresh, mutate } = useRequest(url, {
...options,
manual: true,
formatResult: (res: { data: any }) => res.data,
onSuccess: async (res) => {
SuccessMessage(res.msg);
return true;
},
onError: (e) => {
ErrorNotification(e.message);
return false;
},
throwOnError: true, // 错误时抛出 || when error is thrown and throwOnError is true
refreshOnWindowFocus: true, // 窗口聚焦时 是否重新刷新 || when window focused and refreshOnWindowFocus is true
ready: true, // 初始化状态 || when ready is true and initialData is undefined
debounceInterval: 500, // 防抖间隔 || debounce interval
throttleInterval: 500, // 节流间隔 || throttle interval
initialData: {}, // 初始数据 || init data
defaultLoading: true, // 默认加载 || default loading
loadMore: true // 加载更多 || load more
});
const addData = useCallback(
async (payload: any) => {
await run({
...options,
method: 'POST',
data: payload
});
},
[run, options]
);
const getDataList = useCallback(async () => {
await run({
...options,
method: 'GET'
});
}, [run, options]);
const updateData = useCallback(
async (id: number, payload: any) => {
await run({
...options,
method: 'PUT',
url: `${url}/${id}`,
data: payload
});
},
[run, options, url]
);
const removeDataById = useCallback(
async (id: number) => {
await run({
...options,
method: 'DELETE',
url: `${url}/${id}`
});
},
[run, options, url]
);
return {
data,
error,
loading,
params,
run,
cancel: cancel || noop,
refresh: refresh || (() => Promise.resolve()),
mutate,
addData,
getDataList,
updateData,
removeDataById
};
};
export default useCustomCRUD;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import lodash from 'lodash';
import { SetStateAction, useCallback, useEffect, useRef, useState } from 'react';
interface UseRequestOptionsProps<TData extends { data: any }, TParams extends any[]> {
/*
* 手动开启
*/
manual?: boolean;
/*
* 请求参数
*/
defaultParams: TParams;
/*
* 轮询
*/
pollingInterval?: number | null;
/*
* 准备,用于依赖请求
*/
ready?: boolean;
/*
* 防抖
*/
debounceInterval?: number;
/*
* 节流
*/
throttleInterval?: number;
/*
* 延迟loading为true的时间
*/
loadingDelay?: number;
/*
* 依赖
*/
refreshDeps?: any[];
/*
* 请求成功回调
*/
onSuccess?: (res: TData) => void;
}
function useHookRequest<TData extends { data: any }, TParams extends any[]>(
service: (...args: TParams) => Promise<TData>,
options: UseRequestOptionsProps<TData, TParams>
) {
const [data, setData] = useState<SetStateAction<TData>>();
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>();
const status = useRef<boolean>(false);
const pollingIntervalTimer = useRef<NodeJS.Timeout | null>();
const {
manual = false,
defaultParams,
pollingInterval = null,
ready = true,
debounceInterval = null,
throttleInterval = null,
loadingDelay = null,
refreshDeps = null,
onSuccess = null
} = options;
useEffect(() => {
!manual && ready && run(...defaultParams);
}, [manual, ready, ...(Array.isArray(refreshDeps) ? refreshDeps : [])]);
// 请求
const run = (...params: TParams) => {
if (debounceInterval) {
lodash.debounce(doRun, debounceInterval)(params);
} else if (throttleInterval) {
lodash.throttle(doRun, throttleInterval)(params);
} else {
doRun(params);
}
};
const refresh = () => {
run(...defaultParams);
};
// useRequest业务逻辑
const doRun = async (params: TParams) => {
let finish = false;
try {
//延迟显示loading,防止刷新时闪屏
if (loadingDelay) {
setTimeout(() => {
!finish && setLoading(true);
}, loadingDelay);
} else {
setLoading(true);
}
!status.current && (status.current = true);
//定时刷新
if (pollingInterval && status.current) {
pollingIntervalTimer.current = setTimeout(() => {
status.current && run(...defaultParams);
}, pollingInterval);
}
const res: TData = await service(...params);
setData(res.data);
onSuccess && onSuccess(res.data);
} catch (err) {
err && setError(JSON.stringify(err));
} finally {
finish = true;
setLoading(false);
}
};
const cancel = () => {
if (pollingIntervalTimer.current) {
clearTimeout(pollingIntervalTimer.current);
pollingIntervalTimer.current = null;
status.current && (status.current = false);
}
};
// 缓存
const cachedData = useCallback(() => data, [data]);
return { data, loading, error, run, cancel, cachedData, refresh };
}
export default useHookRequest;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import useUmiRequest from '@ahooksjs/use-request';
import { request } from '@umijs/max';
import { Spin } from 'antd';
import { createContext, memo, useContext, useState } from 'react';
export interface RequestOptions {
url: string;
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
data?: T;
params?: any;
headers?: any;
}
export interface RequestContextType {
useGet: (options: RequestOptions) => void;
}
const METHODS = ['Get', 'Post', 'Put', 'Patch', 'Delete'];
export const RequestContext = createContext<RequestContextType>(null!);
export const RequestProvider = memo(({ children }) => {
const [appLoading, setAppLoading] = useState(false);
const requestWithMethod = async (options: RequestOptions) => {
setAppLoading(true);
const { url, ...opts } = options;
const { data } = await request(url, opts);
setAppLoading(false);
return data;
};
//TODO 封装请求方法
const hooks = {};
METHODS.forEach((method) => {
hooks[`use${method}`] = (url, opts) =>
useUmiRequest(
() => {
setAppLoading(true);
return request(url, { ...opts, method });
},
{
formatResult: (result: { data: any }) => result?.data,
requestMethod: (requestOptions: any) => {
if (typeof requestOptions === 'string') {
return request(requestOptions);
}
if (typeof requestOptions === 'object') {
const { url, ...rest } = requestOptions;
return request(url, rest);
}
throw new Error('request options error');
},
onSuccess: (data) => {
setAppLoading(false);
},
onError: (err) => {
setAppLoading(false);
},
onFinally: () => {
setAppLoading(false);
}
}
);
});
return (
<RequestContext.Provider value={{ ...hooks, appLoading }}>
<Spin tip='网络请求中...' spinning={appLoading}>
{children}
</Spin>
</RequestContext.Provider>
);
});
export const useService = () => useContext(RequestContext);
/****
*
*
import { useService } from '../../hooks/useService';
const {useGet,usePost,usePut,usePatch,useDelete} = useService();
const {data} = useGet('/api/current',{params:{xxxx}})
const {data} = usePost('/api/current',{data:{xxxx}})
const {data} = usePut('/api/current',{data:{xxxx}})
const {data} = usePut('/api/current',{data:{xxxx}})
const {data} = usePatch('/api/current',{data:{xxxx}})
const {data} = useDelete('/api/current',{data:{xxxx}})
console.log(data)
*
*
*/
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment