mirror of https://github.com/msgbyte/tailchat
feat: 在线状态监测与处理用户信息缓存
parent
ce149bdaa8
commit
2a12916428
@ -1,17 +1,36 @@
|
|||||||
import { useQuery } from 'react-query';
|
import { useQuery } from 'react-query';
|
||||||
import { fetchUserInfo, UserBaseInfo } from '../model/user';
|
import {
|
||||||
|
fetchUserInfo,
|
||||||
|
getUserOnlineStatus,
|
||||||
|
UserBaseInfo,
|
||||||
|
} from '../model/user';
|
||||||
|
|
||||||
function buildUseCacheFactory<T>(
|
/**
|
||||||
scope: string,
|
* 用户缓存
|
||||||
fetcher: (id: string) => Promise<T>
|
*/
|
||||||
) {
|
export function useCachedUserInfo(
|
||||||
return (id: string): T | Record<string, never> => {
|
userId: string,
|
||||||
const { data } = useQuery([scope, id], () => fetcher(id));
|
refetch = false
|
||||||
return data ?? {};
|
): UserBaseInfo | Record<string, never> {
|
||||||
};
|
const { data } = useQuery(['user', userId], () => fetchUserInfo(userId), {
|
||||||
|
staleTime: 2 * 60 * 60 * 1000, // 缓存2小时
|
||||||
|
refetchOnMount: refetch ? 'always' : true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return data ?? {};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useCachedUserInfo = buildUseCacheFactory<UserBaseInfo>(
|
/**
|
||||||
'user',
|
* 用户登录状态
|
||||||
fetchUserInfo
|
*/
|
||||||
);
|
export function useCachedOnlineStatus(ids: string[]): boolean[] {
|
||||||
|
const { data } = useQuery(
|
||||||
|
['onlineStatus', ids.join(',')],
|
||||||
|
() => getUserOnlineStatus(ids),
|
||||||
|
{
|
||||||
|
staleTime: 10 * 1000, // 缓存10s
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return data ?? ids.map(() => false);
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue