Fix SWR key logic
This commit is contained in:
parent
d6b6ac6dab
commit
26d7d7e0e0
5 changed files with 41 additions and 22 deletions
33
resources/scripts/plugins/useSWRKey.ts
Normal file
33
resources/scripts/plugins/useSWRKey.ts
Normal file
|
@ -0,0 +1,33 @@
|
|||
import { useDeepCompareMemo } from '@/plugins/useDeepCompareMemo';
|
||||
import { ServerContext } from '@/state/server';
|
||||
import { useStoreState } from '@/state/hooks';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
type Context = string | string[] | (string | number | null | {})[];
|
||||
|
||||
function useSWRKey(context: Context, prefix: string | null = null): string {
|
||||
const key = useDeepCompareMemo((): string => {
|
||||
return (Array.isArray(context) ? context : [context]).map((value) => JSON.stringify(value)).join(':');
|
||||
}, [context]);
|
||||
|
||||
if (!key.trim().length) {
|
||||
throw new Error('Must provide a valid context key to "useSWRKey".');
|
||||
}
|
||||
|
||||
return `swr::${prefix ? `${prefix}:` : ''}${key.trim()}`;
|
||||
}
|
||||
|
||||
function useServerSWRKey(context: Context): string {
|
||||
const uuid = ServerContext.useStoreState((state) => state.server.data?.uuid);
|
||||
|
||||
return useSWRKey(context, `server:${uuid}`);
|
||||
}
|
||||
|
||||
function useUserSWRKey(context: Context): string {
|
||||
const uuid = useStoreState((state) => state.user.data?.uuid);
|
||||
|
||||
return useSWRKey(context, `user:${uuid}`);
|
||||
}
|
||||
|
||||
export default useSWRKey;
|
||||
export { useServerSWRKey, useUserSWRKey };
|
|
@ -1,16 +0,0 @@
|
|||
import { useStoreState } from '@/state/hooks';
|
||||
import { useDeepCompareMemo } from '@/plugins/useDeepCompareMemo';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default (context: string | string[] | (string | number | null | {})[]) => {
|
||||
const uuid = useStoreState((state) => state.user.data?.uuid);
|
||||
const key = useDeepCompareMemo((): string => {
|
||||
return (Array.isArray(context) ? context : [context]).map((value) => JSON.stringify(value)).join(':');
|
||||
}, [context]);
|
||||
|
||||
if (!key.trim().length) {
|
||||
throw new Error('Must provide a valid context key to "useUserSWRContextKey".');
|
||||
}
|
||||
|
||||
return `swr::${uuid || 'unknown'}:${key.trim()}`;
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue