Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.2 KB
Raw Blame
import { useQuery } from '@tanstack/react-query'

import { invoicesKeys } from './keys'
import { head } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'

export type InvoicesCountVariables = {
  slug?: string
}

export async function getInvoicesCount({ slug }: InvoicesCountVariables, signal?: AbortSignal) {
  if (!slug) throw new Error('Slug is required')

  const res = await head('/platform/organizations/{slug}/billing/invoices', {
    params: { path: { slug } },
    signal,
    parseAs: 'text',
  })

  if (res.error) throw (res as any).error
  return Number(res.response.headers.get('X-Total-Count'))
}

export type InvoicesCountData = Awaited<ReturnType<typeof getInvoicesCount>>
export type InvoicesCountError = ResponseError

export const useInvoicesCountQuery = <TData = InvoicesCountData>(
  { slug }: InvoicesCountVariables,
  {
    enabled = true,
    ...options
  }: UseCustomQueryOptions<InvoicesCountData, InvoicesCountError, TData> = {}
) =>
  useQuery<InvoicesCountData, InvoicesCountError, TData>({
    queryKey: invoicesKeys.count(slug),
    queryFn: ({ signal }) => getInvoicesCount({ slug }, signal),
    enabled: enabled && typeof slug !== 'undefined',
    ...options,
  })