studio-queries

作者: supabase

在 Supabase Studio 中進行資料擷取的 React Query 慣例。當需要時使用

npx skills add https://github.com/supabase/supabase --skill studio-queries

Studio Queries & Mutations (React Query)

Follow the patterns in apps/studio/data/. Reference examples:

  • Query options: apps/studio/data/storage/bucket-lifecycle-query.ts (plain) and apps/studio/data/jwt-signing-keys/jwt-signing-keys-query.ts (grantedQueryOptions)
  • Mutation hook: apps/studio/data/storage/versioning/archived-object-restore-mutation.ts
  • Keys: apps/studio/data/edge-functions/keys.ts

Folder Boundaries

  • Keep apps/studio/data/ strictly for React Query queries, mutations, and query keys — never put UI formatting or URL helpers in data/ (colocate those with the feature under components/interfaces/).
  • Pass scoping identifiers (projectRef, clusterId, etc.) explicitly in variables — never read ambient React Context inside data/** hooks.
  • Keep create-*-mutation.ts and update-*-mutation.ts separated; put shared payload builders and types in sibling types.ts / utils.ts files inside the domain folder.
  • Derive response types from generated packages/api-types (see api-types) — fix contract drift at the source rather than hiding it with as unknown as CustomType or defensive Array.isArray(data) ? data : [] shims.

Query Keys

Define a keys.ts per domain. Export *Keys helpers using array keys with as const. Never inline query keys in components.

export const edgeFunctionsKeys = {
  list: (projectRef: string | undefined) => ['projects', projectRef, 'edge-functions'] as const,
  detail: (projectRef: string | undefined, slug: string | undefined) =>
    ['projects', projectRef, 'edge-function', slug, 'detail'] as const,
  metrics: (projectRef: string | undefined, params?: { interval?: string; limit?: number }) =>
    ['projects', projectRef, 'edge-functions', 'metrics', ...(params ? [params] : [])] as const,
}

Key hygiene rules:

  • Never flatten multiple optional positional params with .filter(): [..., limit, offset].filter((v) => v !== undefined) collides when (10, undefined) vs (undefined, 10). Group optional filter/pagination params into one object and spread trailing optional params (...(params ? [params] : [])) so keys.metrics(ref) doubles as the prefix key for invalidation.
  • Never fork/suffix cache keys for the same underlying endpoint (e.g. [...queryKey, 'permission-safe']) — reuse the canonical queryOptions and layer select or fallbacks on top.
  • Pass key-factory keys to invalidateQueries / removeQueries (never manual array-index predicates), and check TanStack Query prefix matching before issuing redundant child invalidations.

Query Options (preferred pattern)

Use queryOptions from @tanstack/react-query so one definition works for both useQuery() and queryClient.fetchQuery().

  • Export domain-prefixed XVariables, XData, and XError types.
  • Implement a private getX(variables, signal?) function that validates required variables, forwards signal, calls handleError(error) on failure, and returns data. Do not export it — use queryClient.fetchQuery(xQueryOptions(...)) for imperative fetching.
  • Export xQueryOptions() gated with enabled on required variables (plus IS_PLATFORM from lib/constants for platform-only queries).
  • Parent isPending trap: when gating on a negated value derived from another async query (e.g. enabled: !isHighAvailability), also gate on !isParentPending (enabled: !isPending && !isHighAvailability) so it does not fire while the parent query is unsettled.
  • Default optional opt-in enable flags to false (safe-by-default), never true.
  • Match query params (such as limit) across sibling consumers so they share one cache entry.
  • Custom polling & retries: apps/studio/data/query-client.ts already skips 4xx (except 429) and retries 429/5xx globally. When writing custom refetchInterval or retry overrides, use a conservative interval (e.g. 5_000ms, never 1_000ms), back off on all error.code >= 400, and retry transient error classes (error.code === 429 || error.code >= 500) rather than individual status codes.
  • Caller overrides & enabled: spread non-enabled options ({ ...xQueryOptions(vars), select, refetchInterval }) freely. Never override enabled directly (e.g. { ...xQueryOptions(vars), enabled: isOpen }) — that clobbers the factory's IS_PLATFORM / required-variable gate. Instead, preserve the factory gate (const opts = xQueryOptions(vars); useQuery({ ...opts, enabled: opts.enabled !== false && isOpen })) or accept an optional 2nd { enabled = true } arg in the factory and AND it with the factory's gates (except grant-gated queries below, which always take caller options as the 2nd arg).
import { queryOptions } from '@tanstack/react-query'

import { xKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import { IS_PLATFORM } from '@/lib/constants'
import type { StudioError } from '@/lib/errors/studio-errors'

export type XVariables = { projectRef?: string }
export type XError = StudioError

async function getX({ projectRef }: XVariables, signal?: AbortSignal) {
  if (!projectRef) throw new Error('projectRef is required')
  const { data, error } = await get('/v1/projects/{ref}/x', {
    params: { path: { ref: projectRef } },
    signal,
  })
  if (error) handleError(error)
  return data
}

export type XData = Awaited<ReturnType<typeof getX>>

export const xQueryOptions = ({ projectRef }: XVariables) =>
  queryOptions<XData, XError>({
    queryKey: xKeys.list(projectRef),
    queryFn: ({ signal }) => getX({ projectRef }, signal),
    enabled: IS_PLATFORM && typeof projectRef !== 'undefined',
  })

Grant-gated Queries

Query options requiring a grant (lib/grants.ts) use grantedQueryOptions from @/data/granted-query-options and accept caller options as the second argument. Never spread or Object.assign them (fga/no-spread-granted-query-options enforces this via the branded __grantedQueryOptions return type).

  • Pass queryFn: undefined (never skipToken, which breaks invalidation when a grant-less observer shares the cache entry) when a grant or required variable is missing; grantedQueryOptions forces enabled: false and supplies a delegating fallback queryFn (avoiding TanStack's dev No queryFn error).
  • The factory owns queryKey, queryFn, and the grant enabled gate so callers cannot override the grant check.
export const xQueryOptions = <TData = XData>(
  { projectRef, grant }: XVariables,
  options?: GrantedQueryCallerOptions<XData, XError, TData, ReturnType<typeof xKeys.list>>
) =>
  grantedQueryOptions(
    {
      queryKey: xKeys.list(projectRef),
      queryFn:
        projectRef && grant ? ({ signal }) => getX({ projectRef, grant }, signal) : undefined,
    },
    options
  )

// Caller
useQuery(xQueryOptions({ projectRef, grant: xGrant.grant }, { select, enabled: open }))

Component & Imperative Usage

// Component
const { data, isPending, isError } = useQuery(xQueryOptions({ projectRef: project?.ref }))

// Imperative (callbacks / outside React) — fetchQuery ignores `enabled`, so mirror factory gates first
const queryClient = useQueryClient()
if (IS_PLATFORM && project?.ref) {
  const data = await queryClient.fetchQuery(xQueryOptions({ projectRef: project.ref }))
}
  • Use React Query v5 flags (isPending for initial load, isFetching for background refetches) and render states in order: pending → error → success.
  • Call query hooks directly in consuming child/modal components instead of fetching in a parent solely to prop-drill data/isPending/isError; use select for single-consumer derived values instead of one-off wrapper hooks.
  • Gate infinite-scroll fetchNextPage() behind !isFetching (or !isFetchingNextPage) to prevent duplicate page requests.
  • Never await mutate(...) (mutate returns void). Prefer mutate + callbacks over mutateAsync unless a Promise is needed (e.g. an async dialog loading state or sequential flow), and always wrap mutateAsync in try/catch (never empty catch { return }).
  • Read mutation error directly from useMutation() instead of mirroring it in useState, and pass cross-callback mutation state via React Query context (onMutate → onSuccess/onSettled) instead of a useRef.

Mutation Hook

  • Export a Variables type (projectRef, identifiers, payload), implement a private updateX(vars) function with variable validation and handleError, and wrap in useXMutation() accepting Omit<UseMutationOptions<...>, 'mutationFn'> (forwarding all 4 TanStack v5 callback args; existing hooks using UseCustomMutationOptions from @/types use a 3-arg callback contract).
  • Don't destructure onSuccess unless adding custom onSuccess logic — otherwise caller onSuccess callbacks are silently swallowed (let ...options forward it).
  • In onSuccess, await Promise.all([...]) to invalidate every view staled by the mutation via key factories, without wiping freshly prefetched keys or unrelated user/resource scopes.
  • Single-layer error toasts: default to toast.error(...) only when onError === undefined; if callers handle errors inline or imperatively via mutateAsync + catch, pass a custom onError (or omit the default toast when all callers handle errors themselves) to avoid duplicate toasts.
import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'
import { toast } from 'sonner'

import { xKeys } from './keys'

type XUpdateVariables = { projectRef: string; slug: string; payload: XPayload }

export const useXUpdateMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<UseMutationOptions<XData, XError, XUpdateVariables>, 'mutationFn'> = {}) => {
  const queryClient = useQueryClient()
  return useMutation<XData, XError, XUpdateVariables>({
    mutationFn: updateX,
    async onSuccess(data, variables, context, mutationContext) {
      await Promise.all([
        queryClient.invalidateQueries({
          queryKey: xKeys.detail(variables.projectRef, variables.slug),
        }),
        queryClient.invalidateQueries({ queryKey: xKeys.list(variables.projectRef) }),
      ])
      await onSuccess?.(data, variables, context, mutationContext)
    },
    async onError(error, variables, context, mutationContext) {
      if (onError === undefined) toast.error(`Failed to update: ${error.message}`)
      else await onError(error, variables, context, mutationContext)
    },
    ...options,
  })
}