import { queryOptions as _createQueryOptions, UseQueryOptions } from '@tanstack/react-query'; import { NamespaceModel } from '~/models/namespace'; import { K8sGetResource, K8sListResourceItems, queryClient } from '../../../k8s'; import { NamespaceKind } from '../../../types'; const LOCAL_STORAGE_NAMESPACE_KEY = 'lastUsedNamespace'; export const NAMESPACE_QUERY_KEY = 'namespace'; export const getLastUsedNamespace = (): string => { return localStorage.getItem(LOCAL_STORAGE_NAMESPACE_KEY); }; export const setLastUsedNamespace = (workspace: string) => { localStorage.setItem(LOCAL_STORAGE_NAMESPACE_KEY, workspace); }; const createNamespaceQueryKey = (name?: string) => { return [NAMESPACE_QUERY_KEY, ...(name ? [name] : [])]; }; function fetchNamespaces(): Promise; function fetchNamespaces(name: string): Promise; function fetchNamespaces(name?: string): Promise { return !name ? K8sListResourceItems({ model: NamespaceModel, fetchOptions: { timeout: 300000 }, // 5 minutes timeout for large namespace lists }) : K8sGetResource({ model: NamespaceModel, queryOptions: { name } }); } export function createNamespaceQueryOptions(): UseQueryOptions; export function createNamespaceQueryOptions(name: string): UseQueryOptions; export function createNamespaceQueryOptions( name?: string, ): UseQueryOptions { return _createQueryOptions({ queryKey: createNamespaceQueryKey(name), queryFn: () => fetchNamespaces(name), initialData: name ? () => { return queryClient .getQueryData([NAMESPACE_QUERY_KEY]) ?.find((w: NamespaceKind) => w.metadata.name === name); } : undefined, staleTime: name ? 5_00_000 : Infinity, }); } export function invalidateNamespaceQuery(): Promise; export function invalidateNamespaceQuery(name: string): Promise; export async function invalidateNamespaceQuery(name?: string): Promise { return await queryClient.invalidateQueries({ queryKey: createNamespaceQueryKey(name) }); } export const queryNamespaces = () => { return queryClient.ensureQueryData(createNamespaceQueryOptions()); };