Files
supabase/apps/studio/data/analytics/warehouse-collections-create-mutation.ts
Jordi Enric f3b4f658a0 feat: add collection retention days (#29469)
* add create collection retention input

* improve spacing between inputs, add 'days' suffix to input

* add dynamic input description clarifying days and max days for retention

* add admonition and upgrade plan link

* only show admonition on free tier

* update desc

* undo
2024-09-27 15:32:10 +02:00

71 lines
2.1 KiB
TypeScript

import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { handleError, post } from 'data/fetchers'
import { toast } from 'sonner'
import type { ResponseError } from 'types'
import { analyticsKeys } from './keys'
export type CreateCollectionArgs = {
projectRef: string
name: string
retention_days: number
}
export async function createCollection({ projectRef, name, retention_days }: CreateCollectionArgs) {
const { data, error } = await post('/platform/projects/{ref}/analytics/warehouse/collections', {
params: { path: { ref: projectRef } },
body: { name, retention_days },
} as any)
if (error) handleError(error)
return data
}
type CreateCollectionData = Awaited<ReturnType<typeof createCollection>>
export const useCreateCollection = ({
onSuccess,
onError,
...options
}: Omit<
UseMutationOptions<CreateCollectionData, ResponseError, CreateCollectionArgs>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<CreateCollectionData, ResponseError, CreateCollectionArgs>(
(vars) => {
// temporal fix
// prevent users from creating collections with the same name
// this will be handled by the backend
// - jordi
const existingCollectionNames = queryClient
.getQueryData<CreateCollectionData[]>(analyticsKeys.warehouseCollections(vars.projectRef))
?.map((c) => c.name)
if (existingCollectionNames?.includes(vars.name)) {
throw new Error(`Collection with the name ${vars.name} already exists`)
}
return createCollection(vars)
},
{
async onSuccess(data, variables, context) {
const { projectRef } = variables
await queryClient.invalidateQueries(analyticsKeys.warehouseCollections(projectRef))
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to create collection: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
}