admin-vben5/apps/web-antd/src/utils/dict.ts

71 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-08-08 14:05:08 +08:00
import { dictDataInfo } from '#/api/system/dict/dict-data';
import { useDictStore } from '#/store/dict';
/**
*
* @param dictName
* @param dataGetter
2025-01-08 12:51:04 +08:00
* @param formatNumber value为number类型
* @returns
*/
function fetchAndCacheDictData<T>(
dictName: string,
dataGetter: () => T[],
2025-01-08 12:51:04 +08:00
formatNumber = false,
): T[] {
const { dictRequestCache, setDictInfo } = useDictStore();
// 有调用方决定如何获取数据
const dataList = dataGetter();
2024-08-08 14:05:08 +08:00
2024-09-05 17:50:04 +08:00
// 检查请求状态缓存
if (dataList.length === 0 && !dictRequestCache.has(dictName)) {
2024-08-08 14:05:08 +08:00
dictRequestCache.set(
dictName,
2024-10-12 14:10:19 +08:00
dictDataInfo(dictName)
.then((resp) => {
// 缓存到store 这样就不用重复获取了
// 内部处理了push的逻辑 这里不用push
2025-01-08 12:51:04 +08:00
setDictInfo(dictName, resp, formatNumber);
2024-10-12 14:10:19 +08:00
})
.finally(() => {
// 移除请求状态缓存
/**
* item为空的情况( item本来就是错误用法)
* if一直进入逻辑导致接口无限刷新
* dictList为空时
*/
if (dataList.length > 0) {
dictRequestCache.delete(dictName);
}
2024-10-12 14:10:19 +08:00
}),
2024-08-08 14:05:08 +08:00
);
}
return dataList;
2024-08-08 14:05:08 +08:00
}
/**
* 使
* @deprecated 使getDictOptions代替
* @param dictName
* @returns
*/
export function getDict(dictName: string) {
const { getDictOptions } = useDictStore();
return fetchAndCacheDictData(dictName, () => getDictOptions(dictName));
}
/**
* Select, Radio, Checkbox等组件使用
* @param dictName
2025-01-08 12:51:04 +08:00
* @param formatNumber value为number类型
* @returns Options数组
*/
2025-01-08 12:51:04 +08:00
export function getDictOptions(dictName: string, formatNumber = false) {
const { getDictOptions } = useDictStore();
2025-01-08 12:51:04 +08:00
return fetchAndCacheDictData(
dictName,
() => getDictOptions(dictName),
formatNumber,
);
2024-08-08 14:05:08 +08:00
}