Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Convert backup restore and download to RQ mutations, and refactor BackupItem to use them

Joshen Limee1e79cc7175
diff --git a/studio/components/interfaces/Database/Backups/BackupItem.tsx b/studio/components/interfaces/Database/Backups/BackupItem.tsx
index ebd1669560f..be03cf13da2 100644
--- a/studio/components/interfaces/Database/Backups/BackupItem.tsx
+++ b/studio/components/interfaces/Database/Backups/BackupItem.tsx
@@ -2,14 +2,14 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
-import { useState } from 'react'
+import { Badge, Button, IconDownload } from 'ui'
import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'
+import { useBackupDownloadMutation } from 'data/database/backup-download-mutation'
+import { useBackupRestoreMutation } from 'data/database/backup-restore-mutation'
import { setProjectStatus } from 'data/projects/projects-query'
import { useCheckPermissions, useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { Badge, Button, IconDownload } from 'ui'
+import { PROJECT_STATUS } from 'lib/constants'
interface BackupItemProps {
projectRef: string
@@ -18,48 +18,33 @@ interface BackupItemProps {
}
const BackupItem = ({ projectRef, backup, index }: BackupItemProps) => {
- const queryClient = useQueryClient()
const router = useRouter()
const { ui } = useStore()
-
- const [isDownloading, setDownloading] = useState<boolean>(false)
- const [isRestoring, setRestoring] = useState<boolean>(false)
+ const queryClient = useQueryClient()
const canTriggerScheduledBackups = useCheckPermissions(
PermissionAction.INFRA_EXECUTE,
'queue_job.restore.prepare'
)
- async function restore(backup: any) {
- setRestoring(true)
- try {
- post(`${API_URL}/database/${projectRef}/backups/restore`, backup).then(() => {
- setTimeout(() => {
- setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
- ui.setNotification({
- category: 'success',
- message: `Restoring database back to ${dayjs(backup.inserted_at).format(
- 'DD MMM YYYY HH:mm:ss'
- )}`,
- })
- router.push(`/project/${projectRef}`)
- }, 3000)
- })
- } catch (error: any) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to restore from backup: ${error.message}`,
- })
- setRestoring(false)
- }
- }
+ const { mutate: restoreFromBackup, isLoading: isRestoring } = useBackupRestoreMutation({
+ onSuccess: () => {
+ setTimeout(() => {
+ setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
+ ui.setNotification({
+ category: 'success',
+ message: `Restoring database back to ${dayjs(backup.inserted_at).format(
+ 'DD MMM YYYY HH:mm:ss'
+ )}`,
+ })
+ router.push(`/project/${projectRef}`)
+ }, 3000)
+ },
+ })
- async function download(backup: any) {
- setDownloading(true)
- try {
- const res = await post(`${API_URL}/database/${projectRef}/backups/download`, backup)
- const { fileUrl } = await res
+ const { mutate: downloadBackup, isLoading: isDownloading } = useBackupDownloadMutation({
+ onSuccess: (res) => {
+ const { fileUrl } = res
// Trigger browser download by create,trigger and remove tempLink
const tempLink = document.createElement('a')
@@ -67,27 +52,16 @@ const BackupItem = ({ projectRef, backup, index }: BackupItemProps) => {
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
+ },
+ })
- setDownloading(false)
- } catch (error: any) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to download backup: ${error.message}`,
- })
- setDownloading(false)
- }
- }
-
- function onRestoreClick() {
+ const onRestoreClick = () => {
confirmAlert({
title: 'Confirm to restore',
message: `Are you sure you want to restore from ${dayjs(backup.inserted_at).format(
'DD MMM YYYY'
)}? This will destroy any new data written since this backup was made.`,
- onAsyncConfirm: async () => {
- await restore(backup)
- },
+ onAsyncConfirm: async () => restoreFromBackup({ ref: projectRef, backup }),
})
}
@@ -108,7 +82,7 @@ const BackupItem = ({ projectRef, backup, index }: BackupItemProps) => {
<Button
type="default"
disabled={!canTriggerScheduledBackups || isRestoring || isDownloading}
- onClick={() => download(backup)}
+ onClick={() => downloadBackup({ ref: projectRef, backup })}
loading={isDownloading}
icon={<IconDownload />}
>
diff --git a/studio/data/database/backup-download-mutation.ts b/studio/data/database/backup-download-mutation.ts
new file mode 100644
index 00000000000..565fbb72de2
--- /dev/null
+++ b/studio/data/database/backup-download-mutation.ts
@@ -0,0 +1,48 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { Backup } from './backup-restore-mutation'
+
+export type BackupDownloadVariables = {
+ ref: string
+ backup: Backup
+}
+
+export async function downloadBackup({ ref, backup }: BackupDownloadVariables) {
+ const { data, error } = await post('/platform/database/{ref}/backups/download', {
+ params: { path: { ref } },
+ body: { ...backup, status: backup.status as unknown as string },
+ })
+ if (error) throw error
+ return data
+}
+
+type BackupDownloadData = Awaited<ReturnType<typeof downloadBackup>>
+
+export const useBackupDownloadMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<BackupDownloadData, ResponseError, BackupDownloadVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<BackupDownloadData, ResponseError, BackupDownloadVariables>(
+ (vars) => downloadBackup(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to download backup: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/database/backup-restore-mutation.ts b/studio/data/database/backup-restore-mutation.ts
new file mode 100644
index 00000000000..983f666be2c
--- /dev/null
+++ b/studio/data/database/backup-restore-mutation.ts
@@ -0,0 +1,51 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { components } from 'data/api'
+
+export type BackupRestoreVariables = {
+ ref: string
+ backup: Backup
+}
+
+// [Joshen] Shift to backups RQ query once created
+export type Backup = components['schemas']['Backup']
+
+export async function restoreFromBackup({ ref, backup }: BackupRestoreVariables) {
+ const { data, error } = await post('/platform/database/{ref}/backups/restore', {
+ params: { path: { ref } },
+ body: { ...backup, status: backup.status as unknown as string },
+ })
+ if (error) throw error
+ return data
+}
+
+type BackupRestoreData = Awaited<ReturnType<typeof restoreFromBackup>>
+
+export const useBackupRestoreMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<BackupRestoreData, ResponseError, BackupRestoreVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<BackupRestoreData, ResponseError, BackupRestoreVariables>(
+ (vars) => restoreFromBackup(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to restore from backup: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}