staff_data/packages/client/src/api/utils.ts

63 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-09-03 20:29:51 +08:00
import { QueryClient } from "@tanstack/react-query";
import { getQueryKey } from "@trpc/react-query";
/**
*
*
* @template T -
* @param {QueryClient} client -
* @param {any} trpcQueryKey -
* @param {string} uniqueField - 'id'
* @returns {T[]} -
*/
export function getCacheDataFromQuery<T>(client: QueryClient, trpcQueryKey: any, uniqueField: string = 'id'): T[] {
// 获取查询缓存数据
const cacheData = client.getQueriesData({ queryKey: getQueryKey(trpcQueryKey) });
// 提取并整理缓存数据
const data = cacheData
.flatMap(cache => cache.slice(1))
.flat()
.filter(item => item !== undefined) as T[];
2024-12-30 08:26:40 +08:00
// console.log('cacheData', cacheData)
// console.log('data', data)
2024-09-03 20:29:51 +08:00
// 使用 Map 进行去重
const uniqueDataMap = new Map<string, T>();
data.forEach((item: T) => {
if (item && item[uniqueField]) {
uniqueDataMap.set(item[uniqueField], item);
}
});
// 转换为数组返回唯一的数据列表
return Array.from(uniqueDataMap.values());
}
/**
*
*
* @template T -
* @param {T[]} uniqueData -
* @param {string} key -
* @param {string} uniqueField - 'id'
* @returns {T | undefined} - undefined
*/
export function findDataByKey<T>(uniqueData: T[], key: string | number, uniqueField: string = 'id'): T | undefined {
return uniqueData.find(item => item[uniqueField] === key);
}
/**
* 使
*
* @template T -
* @param {QueryClient} client -
* @param {any} trpcQueryKey -
* @param {string} key -
* @param {string} uniqueField - 'id'
* @returns {T | undefined} - undefined
*/
export function findQueryData<T>(client: QueryClient, trpcQueryKey: any, key: string | number, uniqueField: string = 'id'): T | undefined {
const uniqueData = getCacheDataFromQuery<T>(client, trpcQueryKey, uniqueField);
return findDataByKey<T>(uniqueData, key, uniqueField);
}
2024-12-30 08:26:40 +08:00