Files
supabase/apps/studio/data/content/content-upsert-mutation.ts
Joshen Lim c153df20c8 Refactor search list in sql editor to have context menu (#37945)
* Refactor search list in sql editor to have context menu

* Add visibility to snippet item in search list tree view

* Address feedback

* Attempt to fix unit test for edit secret modal

* REvert changes to edit secret modal test
2025-08-18 11:26:33 +08:00

73 lines
2.1 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import type { components } from 'data/api'
import { handleError, put } from 'data/fetchers'
import type { ResponseError } from 'types'
import type { Content } from './content-query'
import { contentKeys } from './keys'
export type UpsertContentPayload = Omit<components['schemas']['UpsertContentBody'], 'content'> & {
content: Partial<Content['content']>
}
export type UpsertContentVariables = {
projectRef: string
payload: UpsertContentPayload
}
export async function upsertContent(
{ projectRef, payload }: UpsertContentVariables,
signal?: AbortSignal
) {
const { data, error } = await put('/platform/projects/{ref}/content', {
params: { path: { ref: projectRef } },
body: payload,
headers: { Version: '2' },
signal,
})
if (error) handleError(error)
return data
}
export type UpsertContentData = Awaited<ReturnType<typeof upsertContent>>
export const useContentUpsertMutation = ({
onError,
onSuccess,
invalidateQueriesOnSuccess = true,
...options
}: Omit<
UseMutationOptions<UpsertContentData, ResponseError, UpsertContentVariables>,
'mutationFn'
> & {
invalidateQueriesOnSuccess?: boolean
} = {}) => {
const queryClient = useQueryClient()
return useMutation<UpsertContentData, ResponseError, UpsertContentVariables>(
(args) => upsertContent(args),
{
async onSuccess(data, variables, context) {
const { projectRef } = variables
if (invalidateQueriesOnSuccess) {
await Promise.all([
queryClient.invalidateQueries(contentKeys.allContentLists(projectRef)),
queryClient.invalidateQueries(contentKeys.infiniteList(projectRef)),
])
}
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to insert content: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}