misc_pterodactyl-panel/resources/scripts/plugins/useSWRKey.ts

34 lines
1.1 KiB
TypeScript
Raw Permalink Normal View History

2022-07-04 22:22:58 +00:00
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 => {
2022-11-25 20:25:03 +00:00
return (Array.isArray(context) ? context : [context]).map(value => JSON.stringify(value)).join(':');
2022-07-04 22:22:58 +00:00
}, [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 {
2022-11-25 20:25:03 +00:00
const uuid = ServerContext.useStoreState(state => state.server.data?.uuid);
2022-07-04 22:22:58 +00:00
return useSWRKey(context, `server:${uuid}`);
}
function useUserSWRKey(context: Context): string {
2022-11-25 20:25:03 +00:00
const uuid = useStoreState(state => state.user.data?.uuid);
2022-07-04 22:22:58 +00:00
return useSWRKey(context, `user:${uuid}`);
}
export default useSWRKey;
export { useServerSWRKey, useUserSWRKey };