SPB Git

Repository Public

query.ts 4.0 KB 95 lines typescript

1"use client";2// TanStack Query bindings. Query keys are `[path, {path, query}]` so realtime events can invalidate by path prefix.3import { QueryClient, useQuery, type UseQueryOptions, type UseQueryResult } from "@tanstack/react-query";4import { apiGet, type ApiData, type GetInit, type GetPath } from "./client";5import { ApiError } from "./errors";67export function makeQueryClient(): QueryClient {8  return new QueryClient({9    defaultOptions: {10      queries: {11        staleTime: 10_000,12        gcTime: 5 * 60_000,13        refetchOnWindowFocus: true,14        retry: (count, error) => {15          // never retry what the server answered deliberately; retry transient network/5xx twice16          if (error instanceof ApiError && error.status !== 0 && error.status < 500) return false;17          if (error instanceof ApiError && (error.status === 501 || error.status === 503)) return false;18          return count < 2;19        },20      },21      mutations: { retry: false },22    },23  });24}2526type Extra<T> = Omit<UseQueryOptions<T, ApiError, T, readonly unknown[]>, "queryKey" | "queryFn">;2728export function queryKey<P extends GetPath>(path: P, init?: Pick<GetInit<P>, "path" | "query">): readonly unknown[] {29  return [path, { path: init?.path ?? null, query: init?.query ?? null }];30}3132/** `useApiQuery("/nodes", { query: { site } })` — data, error (ApiError) and freshness metadata from TanStack Query. */33export function useApiQuery<P extends GetPath>(path: P, init?: Pick<GetInit<P>, "path" | "query">, options?: Extra<ApiData<P>>): UseQueryResult<ApiData<P>, ApiError> {34  return useQuery<ApiData<P>, ApiError, ApiData<P>, readonly unknown[]>({35    queryKey: queryKey(path, init),36    queryFn: ({ signal }) => (apiGet as (p: P, i: unknown) => Promise<ApiData<P>>)(path, { ...init, signal }),37    ...options,38  });39}4041/** Invalidate every cached query whose path starts with one of the prefixes. */42export function invalidatePaths(qc: QueryClient, ...prefixes: string[]): Promise<void> {43  return qc.invalidateQueries({44    predicate: (q) => {45      const k = q.queryKey[0];46      return typeof k === "string" && prefixes.some((p) => k === p || k.startsWith(p + "/") || k.startsWith(p + "?"));47    },48  });49}5051// ── cursor-paginated lists ──52import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query";5354type ListPath = { [P in GetPath]: ApiData<P> extends { items: unknown[] } ? P : never }[GetPath];55type ItemOf<P extends GetPath> = ApiData<P> extends { items: (infer I)[] } ? I : never;5657export interface ListResult<I> {58  items: I[];59  isLoading: boolean;60  isFetching: boolean;61  error: ApiError | null;62  hasMore: boolean;63  loadingMore: boolean;64  loadMore: () => void;65  refetch: () => void;66  updatedAt: number;67  /** true once at least one page has been received */68  ready: boolean;69}7071/** `useApiList("/alerts", { query: { state: "firing" } })` — follows `next_cursor` on demand. */72export function useApiList<P extends ListPath>(path: P, init?: Pick<GetInit<P>, "path" | "query">, options?: { enabled?: boolean; refetchInterval?: number }): ListResult<ItemOf<P>> {73  type Page = { items: ItemOf<P>[]; next_cursor?: string };74  const q = useInfiniteQuery<Page, ApiError, InfiniteData<Page>, readonly unknown[], string | undefined>({75    queryKey: [path, { path: init?.path ?? null, query: init?.query ?? null }, "list"],76    initialPageParam: undefined,77    queryFn: ({ pageParam, signal }) =>78      (apiGet as (p: P, i: unknown) => Promise<Page>)(path, { ...init, query: { ...(init?.query as object | undefined), ...(pageParam ? { cursor: pageParam } : {}) }, signal }),79    getNextPageParam: (last) => last.next_cursor || undefined,80    ...options,81  });82  return {83    items: q.data?.pages.flatMap((p) => p.items) ?? [],84    isLoading: q.isLoading,85    isFetching: q.isFetching,86    error: q.error,87    hasMore: q.hasNextPage,88    loadingMore: q.isFetchingNextPage,89    loadMore: () => void q.fetchNextPage(),90    refetch: () => void q.refetch(),91    updatedAt: q.dataUpdatedAt,92    ready: q.data !== undefined,93  };94}95
Files main
Menu

Theme