Files
supabase/apps/studio/data/table-editor/table-editor-query.ts
Ivan Vasilov 8b657165b5 chore: Migrate to use custom type for ReactQuery queries and mutations (#40073)
* Add custom types for queries, mutations and infinite queries.

* Migrate all queries to use the new type.

* Migrate all infinite queries to useCustomInfiniteQueryOptions.

* Migrate all mutations to use useCustomMutationOptions.

* Add type to all imports in `types` folder.
2025-11-03 13:18:13 +01:00

78 lines
2.0 KiB
TypeScript

import { QueryClient, useQuery } from '@tanstack/react-query'
import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
import { tableEditorKeys } from './keys'
import { getTableEditorSql } from './table-editor-query-sql'
import { Entity } from './table-editor-types'
import { UseCustomQueryOptions } from 'types'
type TableEditorArgs = {
id?: number
}
export type TableEditorVariables = TableEditorArgs & {
projectRef?: string
connectionString?: string | null
}
export async function getTableEditor(
{ projectRef, connectionString, id }: TableEditorVariables,
signal?: AbortSignal
) {
if (!id) {
throw new Error('id is required')
}
const sql = getTableEditorSql(id)
const { result } = await executeSql(
{
projectRef,
connectionString,
sql,
queryKey: ['table-editor', id],
},
signal
)
return (result[0]?.entity ?? null) as Entity | undefined
}
export type TableEditorData = Awaited<ReturnType<typeof getTableEditor>>
export type TableEditorError = ExecuteSqlError
export const useTableEditorQuery = <TData = TableEditorData>(
{ projectRef, connectionString, id }: TableEditorVariables,
{
enabled = true,
...options
}: UseCustomQueryOptions<TableEditorData, TableEditorError, TData> = {}
) =>
useQuery<TableEditorData, TableEditorError, TData>({
queryKey: tableEditorKeys.tableEditor(projectRef, id),
queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal),
enabled:
enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id),
refetchOnWindowFocus: false,
refetchOnMount: false,
staleTime: 5 * 60 * 1000,
...options,
})
export function prefetchTableEditor(
client: QueryClient,
{ projectRef, connectionString, id }: TableEditorVariables
) {
return client.fetchQuery({
queryKey: tableEditorKeys.tableEditor(projectRef, id),
queryFn: ({ signal }) =>
getTableEditor(
{
projectRef,
connectionString,
id,
},
signal
),
})
}