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

65 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-08-08 14:05:08 +08:00
import type { DictData } from '#/api/system/dict/dict-data-model';
import { dictDataInfo } from '#/api/system/dict/dict-data';
import { type Option, useDictStore } from '#/store/dict';
2024-09-12 16:06:11 +08:00
// todo 重复代码的封装
2024-08-08 14:05:08 +08:00
export function getDict(dictName: string): DictData[] {
2024-09-12 16:06:11 +08:00
const { dictRequestCache, getDict, setDictInfo } = useDictStore();
2024-08-08 14:05:08 +08:00
// 这里拿到
const dictList = getDict(dictName);
2024-09-05 17:50:04 +08:00
// 检查请求状态缓存
if (dictList.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
setDictInfo(dictName, resp);
})
.finally(() => {
// 移除请求状态缓存
/**
* item为空的情况( item本来就是错误用法)
* if一直进入逻辑导致接口无限刷新
* dictList为空时
*/
if (dictList.length > 0) {
dictRequestCache.delete(dictName);
}
2024-10-12 14:10:19 +08:00
}),
2024-08-08 14:05:08 +08:00
);
}
return dictList;
}
export function getDictOptions(dictName: string): Option[] {
2024-09-12 16:06:11 +08:00
const { dictRequestCache, getDictOptions, setDictInfo } = useDictStore();
2024-08-08 14:05:08 +08:00
const dictOptionList = getDictOptions(dictName);
2024-09-05 17:50:04 +08:00
// 检查请求状态缓存
if (dictOptionList.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
setDictInfo(dictName, resp);
})
.finally(() => {
// 移除请求状态缓存
/**
* item为空的情况( item本来就是错误用法)
* if一直进入逻辑导致接口五线刷新
* dictList为空时
*/
if (dictOptionList.length > 0) {
dictRequestCache.delete(dictName);
}
2024-10-12 14:10:19 +08:00
}),
2024-08-08 14:05:08 +08:00
);
}
return dictOptionList;
}