expo-duooomi-app/hooks/actions/use-template-actions.ts

97 lines
2.5 KiB
TypeScript

import { root } from '@repo/core'
import {
type CreateTemplateGenerationInput,
type RerunTemplateSchema,
type RunTemplateInput,
TemplateController,
TemplateGenerationController,
} from '@repo/sdk'
import { useCallback, useState } from 'react'
import type z from 'zod'
import { type ApiError } from '@/lib/types'
import { handleError } from '../data/use-error'
export const useTemplateActions = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const reRunTemplate = useCallback(async (params: z.infer<typeof RerunTemplateSchema>) => {
setLoading(true)
setError(null)
const template = root.get(TemplateController)
const { data, error } = await handleError(async () => await template.rerun(params))
if (error) {
setError(error)
setLoading(false)
return { generationId: null, error }
}
setLoading(false)
return { generationId: data?.generationId, error: null }
}, [])
const runTemplate = useCallback(async (params: RunTemplateInput) => {
setLoading(true)
setError(null)
const template = root.get(TemplateController)
const { data, error } = await handleError(async () => await template.run(params))
if (error) {
setError(error)
setLoading(false)
return { generationId: null, error }
}
setLoading(false)
return { generationId: data?.generationId, error: null }
}, [])
const deleteGeneration = useCallback(async (id: string) => {
setLoading(true)
setError(null)
const templateGeneration = root.get(TemplateGenerationController)
const { data, error } = await handleError(async () => await templateGeneration.delete({ id }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: true, message: data?.message, error: null }
}, [])
const batchDeleteGenerations = useCallback(async (ids: string[]) => {
setLoading(true)
setError(null)
const templateGeneration = root.get(TemplateGenerationController)
const { data, error } = await handleError(async () => await templateGeneration.batchDelete({ ids }))
if (error) {
setError(error)
setLoading(false)
return { success: false, error }
}
setLoading(false)
return { success: true, message: data?.message, error: null }
}, [])
return {
loading,
error,
runTemplate,
deleteGeneration,
batchDeleteGenerations,
reRunTemplate,
}
}