Files
supabase/apps/studio/data/content/content-id-query.ts
Charis Lam cc5548dbe0 refactor(studio): unify snippet save + persistence into SnippetStatus
PR 3 of a stacked refactor. Replaces the two overlapping pieces of snippet
lifecycle state — the savingStates map ('IDLE'|'UPDATING'|'UPDATING_FAILED')
and the isNotSavedInDatabaseYet boolean — with a single SnippetStatus enum.

Save progress and persistence are orthogonal, so the never-persisted 'new'
phase keeps its own saving/failed variants (new, new_saving, new_save_failed)
alongside the persisted ones (saved, unsaved, saving, save_failed). The
wasNeverPersisted() predicate recovers the persistence axis and stays true
across the entire first-save lifecycle, so content-fetching, list
invalidation, and the replication-lag 404 swallow all map faithfully — and a
new snippet's first save keeps its saving/failed indicator.

Status is attached at the data layer so a snippet is never without one:
- SnippetStatus + SnippetWithContent now live in data/content; the snippet
  queries attach status 'saved' via withSavedStatus(), and upsertContent
  returns SnippetWithContent so move/rename responses carry status too.
- A SQL-typed getSqlSnippetById/useSqlSnippetByIdQuery returns
  SnippetWithContent (the generic useContentIdQuery stays for Reports), so
  [id].tsx loads content with no casting.
- 'new' is attached on local creation (createSqlSnippetSkeletonV2).

Dependents import SnippetWithContent/SnippetStatus directly from the data
layer (no state-layer re-exports). 'unsaved' is reserved for manual-save
dirty tracking in a later PR. Pure unit tests for every predicate/transition.
2026-06-23 18:50:55 -04:00

84 lines
3.2 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { components } from 'api-types'
import type { Content } from './content-query'
import { remapSqlContentField } from './content-remap'
import { contentKeys } from './keys'
import type { SnippetWithContent } from './sql-folders-query'
import { get, handleError } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'
export type GetUserContentByIdResponse = Omit<
components['schemas']['GetUserContentByIdResponse'],
'content'
> & {
content: Content['content']
}
export async function getContentById(
{ projectRef, id }: { projectRef?: string; id?: string },
signal?: AbortSignal
) {
if (typeof projectRef === 'undefined') throw new Error('projectRef is required')
if (typeof id === 'undefined') throw new Error('Content ID is required')
const { data, error } = await get('/platform/projects/{ref}/content/item/{id}', {
params: { path: { ref: projectRef, id } },
signal,
})
if (error) throw handleError(error)
return remapSqlContentField(data as unknown as GetUserContentByIdResponse)
}
export type ContentIdData = Awaited<ReturnType<typeof getContentById>>
export type ContentIdError = ResponseError
// SQL-editor-specific fetch: the editor only ever loads SQL snippets, so the
// content body is typed as SQL content and the result is a SnippetWithContent
// (status 'saved') ready to drop into the store — no narrowing/casting at the
// call site. Reports etc. keep using the generic getContentById above.
export async function getSqlSnippetById(
{ projectRef, id }: { projectRef?: string; id?: string },
signal?: AbortSignal
): Promise<SnippetWithContent> {
if (typeof projectRef === 'undefined') throw new Error('projectRef is required')
if (typeof id === 'undefined') throw new Error('Content ID is required')
const { data, error } = await get('/platform/projects/{ref}/content/item/{id}', {
params: { path: { ref: projectRef, id } },
signal,
})
if (error) throw handleError(error)
const snippet = remapSqlContentField(data as unknown as Omit<SnippetWithContent, 'status'>)
return { ...snippet, status: 'saved' }
}
export type SqlSnippetByIdData = Awaited<ReturnType<typeof getSqlSnippetById>>
export const useSqlSnippetByIdQuery = <TData = SqlSnippetByIdData>(
{ projectRef, id }: { projectRef?: string; id?: string },
{
enabled = true,
...options
}: UseCustomQueryOptions<SqlSnippetByIdData, ContentIdError, TData> = {}
) =>
useQuery<SqlSnippetByIdData, ContentIdError, TData>({
queryKey: contentKeys.resource(projectRef, id),
queryFn: ({ signal }) => getSqlSnippetById({ projectRef, id }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
...options,
})
export const useContentIdQuery = <TData = ContentIdData>(
{ projectRef, id }: { projectRef?: string; id?: string },
{ enabled = true, ...options }: UseCustomQueryOptions<ContentIdData, ContentIdError, TData> = {}
) =>
useQuery<ContentIdData, ContentIdError, TData>({
queryKey: contentKeys.resource(projectRef, id),
queryFn: ({ signal }) => getContentById({ projectRef, id }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
...options,
})