UNPKG

@supabase-cache-helpers/postgrest-react-query

Version:

A collection of React Query utilities for working with Supabase.

240 lines (220 loc) 19.8 kB
import * as _supabase_cache_helpers_postgrest_core from '@supabase-cache-helpers/postgrest-core'; import { DeleteItemOperation, MutateItemOperation, UpsertItemOperation, PostgrestQueryParserOptions, PostgrestFilter, DecodedKey, RevalidateOpts, InsertFetcherOptions, UpdateFetcherOptions, UpsertFetcherOptions, DeleteFetcherOptions, AnyPostgrestResponse } from '@supabase-cache-helpers/postgrest-core'; export { PostgrestHasMorePaginationCacheData, PostgrestPaginationCacheData } from '@supabase-cache-helpers/postgrest-core'; import * as _tanstack_react_query from '@tanstack/react-query'; import { UseMutationOptions, UseQueryOptions, QueryClient, FetchQueryOptions, UseQueryResult, MutationOptions } from '@tanstack/react-query'; import * as _supabase_postgrest_js from '@supabase/postgrest-js'; import { PostgrestQueryBuilder, PostgrestError as PostgrestError$1, PostgrestSingleResponse, PostgrestMaybeSingleResponse, PostgrestResponse } from '@supabase/postgrest-js'; import { GetResult } from '@supabase/postgrest-js/dist/module/select-query-parser'; import { GenericSchema, GenericTable } from '@supabase/postgrest-js/dist/module/types'; import { PostgrestError, RealtimePostgresChangesPayload, SupabaseClient, RealtimePostgresChangesFilter, REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, RealtimeChannel } from '@supabase/supabase-js'; /** * Convenience hook to delete an item from the react query cache. Does not make any http requests, and is supposed to be used for custom cache updates. * @param opts The mutation options * @returns void */ declare function useDeleteItem<Type extends Record<string, unknown>>(opts: Omit<DeleteItemOperation<Type>, 'input'>): (input: Type) => Promise<void>; /** * Convenience hook to mutate an item within the react query cache. Does not make any http requests, and is supposed to be used for custom cache updates. * @param opts The mutation options * @returns void */ declare function useMutateItem<Type extends Record<string, unknown>>(opts: Omit<MutateItemOperation<Type>, 'input' | 'mutate'>): (input: Partial<Type>, mutateFn: (current: Type) => Type) => Promise<void>; /** * Convenience hook to upsert an item into the react query cache. Does not make any http requests, and is supposed to be used for custom cache updates. * @param opts The mutation options * @returns void */ declare function useUpsertItem<Type extends Record<string, unknown>>(opts: Omit<UpsertItemOperation<Type>, 'input'>): (input: Type) => Promise<void>; declare const POSTGREST_FILTER_KEY_PREFIX = "postgrest-filter"; declare const usePostgrestFilterCache: <R extends Record<string, unknown>>() => (query: string, opts?: PostgrestQueryParserOptions) => PostgrestFilter<any>; declare const KEY_PREFIX = "postgrest"; declare const INFINITE_KEY_PREFIX = "page"; type DecodedReactQueryKey = DecodedKey & { isInfinite: boolean; key: string[]; }; declare const encode: <Result>(key: unknown, isInfinite: boolean) => string[]; declare const decode: (key: unknown) => DecodedReactQueryKey | null; declare const useQueriesForTableLoader: (table: string) => () => { paths: _supabase_cache_helpers_postgrest_core.Path[]; filters: _supabase_cache_helpers_postgrest_core.FilterDefinitions; }[]; type Operation = 'Insert' | 'UpdateOne' | 'Upsert' | 'DeleteOne' | 'DeleteMany'; type GetFetcherOptions<S extends GenericSchema, T extends GenericTable, O extends Operation> = O extends 'Insert' ? InsertFetcherOptions<S, T> : O extends 'UpdateOne' ? UpdateFetcherOptions<S, T> : O extends 'Upsert' ? UpsertFetcherOptions<S, T> : O extends 'DeleteOne' | 'DeleteMany' ? DeleteFetcherOptions<S, T> : never; type GetInputType<T extends GenericTable, O extends Operation> = O extends 'DeleteOne' ? Partial<T['Row']> : O extends 'DeleteMany' ? Partial<T['Row']>[] : O extends 'Insert' | 'Upsert' ? T['Insert'][] : O extends 'UpdateOne' ? T['Update'] : never; type GetReturnType<S extends GenericSchema, T extends GenericTable, RelationName, Relationships, O extends Operation, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Relationships, Q extends '*' ? '*' : Q>> = O extends 'UpdateOne' ? R | null : O extends 'DeleteOne' ? R | null : O extends 'Insert' | 'Upsert' | 'DeleteMany' ? R[] | null : never; type UsePostgrestMutationOpts<S extends GenericSchema, T extends GenericTable, RelationName, Relationships, O extends Operation, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Relationships, Q extends '*' ? '*' : Q>> = RevalidateOpts<T['Row']> & UseMutationOptions<GetReturnType<S, T, RelationName, Relationships, O, Q, R> | null, PostgrestError, GetInputType<T, O>> & { disableAutoQuery?: boolean; } & GetFetcherOptions<S, T, O>; /** * Hook to execute a DELETE mutation * * @param {PostgrestQueryBuilder<S, T>} qb PostgrestQueryBuilder instance for the table * @param {Array<keyof T['Row']>} primaryKeys Array of primary keys of the table * @param {string | null} query Optional PostgREST query string for the DELETE mutation * @param {Omit<UsePostgrestMutationOpts<S, T, 'DeleteOne', Q, R>, 'mutationFn'>} [opts] Options to configure the hook */ declare function useDeleteManyMutation<S extends GenericSchema, T extends GenericTable, RelationName, Re = T extends { Relationships: infer R; } ? R : unknown, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Re, Q extends '*' ? '*' : Q>>(qb: PostgrestQueryBuilder<S, T, Re>, primaryKeys: (keyof T['Row'])[], query?: Q | null, opts?: Omit<UsePostgrestMutationOpts<S, T, RelationName, Re, 'DeleteMany', Q, R>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<R[] | null, _supabase_postgrest_js.PostgrestError, Partial<T["Row"]>[], unknown>; /** * Hook to execute a DELETE mutation * * @param {PostgrestQueryBuilder<S, T>} qb PostgrestQueryBuilder instance for the table * @param {Array<keyof T['Row']>} primaryKeys Array of primary keys of the table * @param {string | null} query Optional PostgREST query string for the DELETE mutation * @param {Omit<UsePostgrestMutationOpts<S, T, 'DeleteOne', Q, R>, 'mutationFn'>} [opts] Options to configure the hook */ declare function useDeleteMutation<S extends GenericSchema, T extends GenericTable, RelationName, Re = T extends { Relationships: infer R; } ? R : unknown, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Re, Q extends '*' ? '*' : Q>>(qb: PostgrestQueryBuilder<S, T, Re>, primaryKeys: (keyof T['Row'])[], query?: Q | null, opts?: Omit<UsePostgrestMutationOpts<S, T, RelationName, Re, 'DeleteOne', Q, R>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<NonNullable<R> | null, _supabase_postgrest_js.PostgrestError, Partial<T["Row"]>, unknown>; /** * Hook to execute a INSERT mutation * * @param {PostgrestQueryBuilder<S, T>} qb PostgrestQueryBuilder instance for the table * @param {Array<keyof T['Row']>} primaryKeys Array of primary keys of the table * @param {string | null} query Optional PostgREST query string for the INSERT mutation * @param {Omit<UsePostgrestMutationOpts<S, T, 'Insert', Q, R>, 'mutationFn'>} [opts] Options to configure the hook */ declare function useInsertMutation<S extends GenericSchema, T extends GenericTable, RelationName, Re = T extends { Relationships: infer R; } ? R : unknown, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Re, Q extends '*' ? '*' : Q>>(qb: PostgrestQueryBuilder<S, T, Re>, primaryKeys: (keyof T['Row'])[], query?: Q | null, opts?: Omit<UsePostgrestMutationOpts<S, T, RelationName, Re, 'Insert', Q, R>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<(R extends false | "" | 0 | null | undefined ? never : R)[] | null, _supabase_postgrest_js.PostgrestError, T["Insert"][], unknown>; /** * Hook to execute a UPDATE mutation * * @param {PostgrestQueryBuilder<S, T>} qb PostgrestQueryBuilder instance for the table * @param {Array<keyof T['Row']>} primaryKeys Array of primary keys of the table * @param {string | null} query Optional PostgREST query string for the UPDATE mutation * @param {Omit<UsePostgrestMutationOpts<S, T, 'UpdateOne', Q, R>, 'mutationFn'>} [opts] Options to configure the hook */ declare function useUpdateMutation<S extends GenericSchema, T extends GenericTable, RelationName, Re = T extends { Relationships: infer R; } ? R : unknown, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Re, Q extends '*' ? '*' : Q>>(qb: PostgrestQueryBuilder<S, T, Re>, primaryKeys: (keyof T['Row'])[], query?: Q | null, opts?: Omit<UsePostgrestMutationOpts<S, T, RelationName, Re, 'UpdateOne', Q, R>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<NonNullable<R> | null, _supabase_postgrest_js.PostgrestError, T["Update"], unknown>; /** * Hook to execute a UPSERT mutation * * @param {PostgrestQueryBuilder<S, T>} qb PostgrestQueryBuilder instance for the table * @param {Array<keyof T['Row']>} primaryKeys Array of primary keys of the table * @param {string | null} query Optional PostgREST query string for the UPSERT mutation * @param {Omit<UsePostgrestMutationOpts<S, T, 'Upsert', Q, R>, 'mutationFn'>} [opts] Options to configure the hook */ declare function useUpsertMutation<S extends GenericSchema, T extends GenericTable, RelationName, Re = T extends { Relationships: infer R; } ? R : unknown, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Re, Q extends '*' ? '*' : Q>>(qb: PostgrestQueryBuilder<S, T, Re>, primaryKeys: (keyof T['Row'])[], query?: Q | null, opts?: Omit<UsePostgrestMutationOpts<S, T, RelationName, Re, 'Upsert', Q, R>, 'mutationFn'>): _tanstack_react_query.UseMutationResult<(R extends false | "" | 0 | null | undefined ? never : R)[] | null, _supabase_postgrest_js.PostgrestError, T["Insert"][], unknown>; declare function buildQueryOpts<Result>(query: PromiseLike<AnyPostgrestResponse<Result>>, config?: Omit<UseQueryOptions<AnyPostgrestResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): UseQueryOptions<AnyPostgrestResponse<Result>, PostgrestError$1>; declare function fetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestSingleResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<PostgrestSingleResponse<Result>>; declare function fetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestMaybeSingleResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestMaybeSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<PostgrestMaybeSingleResponse<Result>>; declare function fetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<PostgrestResponse<Result>>; declare function prefetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestSingleResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<void>; declare function prefetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestMaybeSingleResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestMaybeSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<void>; declare function prefetchQuery<Result>(queryClient: QueryClient, query: PromiseLike<PostgrestResponse<Result>>, config?: Omit<FetchQueryOptions<PostgrestResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): Promise<void>; declare function fetchQueryInitialData<Result>(query: PromiseLike<PostgrestSingleResponse<Result>>): Promise<[string[], PostgrestSingleResponse<Result>]>; declare function fetchQueryInitialData<Result>(query: PromiseLike<PostgrestMaybeSingleResponse<Result>>): Promise<[string[], PostgrestMaybeSingleResponse<Result>]>; declare function fetchQueryInitialData<Result>(query: PromiseLike<PostgrestResponse<Result>>): Promise<[string[], PostgrestResponse<Result>]>; /** * Represents the return value of the `useQuery` hook when `query` is expected to return * a single row. */ type UseQuerySingleReturn<Result> = Omit<UseQueryResult<PostgrestSingleResponse<Result>['data'], PostgrestError$1>, 'refetch'> & Pick<UseQueryResult<PostgrestSingleResponse<Result>, PostgrestError$1>, 'refetch'> & Pick<PostgrestSingleResponse<Result>, 'count'>; /** * Represents the return value of the `useQuery` hook when `query` is expected to return * either a single row or an empty response. */ type UseQueryMaybeSingleReturn<Result> = Omit<UseQueryResult<PostgrestMaybeSingleResponse<Result>['data'], PostgrestError$1>, 'refetch'> & Pick<UseQueryResult<PostgrestMaybeSingleResponse<Result>, PostgrestError$1>, 'refetch'> & Pick<PostgrestMaybeSingleResponse<Result>, 'count'>; /** * Represents the return value of the `useQuery` hook when `query` is expected to return * one or more rows. */ type UseQueryReturn<Result> = Omit<UseQueryResult<PostgrestResponse<Result>['data'], PostgrestError$1>, 'refetch'> & Pick<UseQueryResult<PostgrestResponse<Result>, PostgrestError$1>, 'refetch'> & Pick<PostgrestResponse<Result>, 'count'>; /** * Represents the return value of the `useQuery` hook when the type of the query response * is not known. */ type UseQueryAnyReturn<Result> = Omit<UseQueryResult<AnyPostgrestResponse<Result>['data'], PostgrestError$1>, 'refetch'> & Pick<UseQueryResult<AnyPostgrestResponse<Result>, PostgrestError$1>, 'refetch'> & Pick<AnyPostgrestResponse<Result>, 'count'>; /** * React hook to execute a PostgREST query and return a single item response. * * @param {PromiseLike<PostgrestSingleResponse<Result>>} query A promise that resolves to a PostgREST single item response. * @param {Omit<UseReactQueryOptions<PostgrestSingleResponse<Result>, PostgrestError>, 'queryKey' | 'queryFn'>} [config] The React Query options. * @returns {UseQuerySingleReturn<Result>} The hook result containing the single item response data. */ declare function useQuery<Result>(query: PromiseLike<PostgrestSingleResponse<Result>>, config?: Omit<UseQueryOptions<PostgrestSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): UseQuerySingleReturn<Result>; /** * React hook to execute a PostgREST query and return a maybe single item response. * * @param {PromiseLike<PostgrestMaybeSingleResponse<Result>>} query A promise that resolves to a PostgREST maybe single item response. * @param {Omit<UseReactQueryOptions<PostgrestMaybeSingleResponse<Result>, PostgrestError>, 'queryKey' | 'queryFn'>} [config] The React Query options. * @returns {UseQueryMaybeSingleReturn<Result>} The hook result containing the maybe single item response data. */ declare function useQuery<Result>(query: PromiseLike<PostgrestMaybeSingleResponse<Result>>, config?: Omit<UseQueryOptions<PostgrestMaybeSingleResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): UseQueryMaybeSingleReturn<Result>; /** * React hook to execute a PostgREST query. * * @template Result The expected response data type. * @param {PromiseLike<PostgrestResponse<Result>>} query A promise that resolves to a PostgREST response. * @param {Omit<UseReactQueryOptions<PostgrestResponse<Result>, PostgrestError>, 'queryKey' | 'queryFn'>} [config] The React Query options. * @returns {UseQueryReturn<Result>} The hook result containing the response data. */ declare function useQuery<Result>(query: PromiseLike<PostgrestResponse<Result>>, config?: Omit<UseQueryOptions<PostgrestResponse<Result>, PostgrestError$1>, 'queryKey' | 'queryFn'>): UseQueryReturn<Result>; /** * Options for `useSubscriptionQuery` hook */ type UseSubscriptionQueryOpts<S extends GenericSchema, T extends GenericTable, RelationName, Relatsonships, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Relatsonships, Q extends '*' ? '*' : Q>> = RevalidateOpts<T['Row']> & MutationOptions & { /** * A callback that will be called whenever a realtime event occurs for the given channel. * The callback will receive the event payload with an additional "data" property, which will be * the affected row of the event (or a modified version of it, if a select query is provided). */ callback?: (event: RealtimePostgresChangesPayload<T['Row']> & { data: T['Row'] | R; }) => void | Promise<void>; }; /** * A hook for subscribing to realtime Postgres events on a given channel. * * The subscription will automatically update the cache for the specified table in response * to incoming Postgres events, and optionally run a user-provided callback function with the * event and the updated data. * * This hook works by creating a Supabase Realtime channel for the specified table and * subscribing to Postgres changes on that channel. When an event is received, the hook * fetches the updated data from the database (using a `select` query generated from the cache * configuration), and then updates the cache accordingly. * * @param client - The Supabase client instance. * @param channelName - The name of the channel to subscribe to. * @param filter - The filter object to use when listening for changes. * @param primaryKeys - An array of the primary keys for the table being listened to. * @param query - An optional PostgREST query to use when selecting data for an event. * @param opts - Additional options to pass to the hook. * @returns An object containing the RealtimeChannel and the current status of the subscription. */ declare function useSubscriptionQuery<S extends GenericSchema, T extends GenericTable, RelationName, Relationships, Q extends string = '*', R = GetResult<S, T['Row'], RelationName, Relationships, Q extends '*' ? '*' : Q>>(client: SupabaseClient | null, channelName: string, filter: Omit<RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, 'table'> & { table: string; }, primaryKeys: (keyof T['Row'])[], query?: Q extends '*' ? "'*' is not allowed" : Q | null, opts?: UseSubscriptionQueryOpts<S, T, RelationName, Relationships, Q, R>): { channel: RealtimeChannel | undefined; status: string | undefined; }; /** * Options for the `useSubscription` hook. */ type UseSubscriptionOpts<T extends GenericTable> = RevalidateOpts<T['Row']> & MutationOptions & { callback?: (event: RealtimePostgresChangesPayload<T['Row']>) => void | Promise<void>; }; /** * Hook that sets up a real-time subscription to a Postgres database table. * * @param channel - The real-time channel to subscribe to. * @param filter - A filter that specifies the table and conditions for the subscription. * @param primaryKeys - An array of primary key column names for the table. * @param opts - Options for the mutation function used to upsert or delete rows in the cache. * * @returns An object containing the current status of the subscription. */ declare function useSubscription<T extends GenericTable>(client: SupabaseClient | null, channelName: string, filter: Omit<RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>, 'table'> & { table: string; }, primaryKeys: (keyof T['Row'])[], opts?: UseSubscriptionOpts<T>): { status: string | undefined; }; export { type DecodedReactQueryKey, INFINITE_KEY_PREFIX, KEY_PREFIX, POSTGREST_FILTER_KEY_PREFIX, type UseQueryAnyReturn, type UseQueryMaybeSingleReturn, type UseQueryReturn, type UseQuerySingleReturn, type UseSubscriptionOpts, type UseSubscriptionQueryOpts, buildQueryOpts, decode, encode, fetchQuery, fetchQueryInitialData, prefetchQuery, useDeleteItem, useDeleteManyMutation, useDeleteMutation, useInsertMutation, useMutateItem, usePostgrestFilterCache, useQueriesForTableLoader, useQuery, useSubscription, useSubscriptionQuery, useUpdateMutation, useUpsertItem, useUpsertMutation };