expo-duooomi-app/hooks/actions/use-file-upload.ts

71 lines
1.8 KiB
TypeScript

import { ApiError } from "@/lib/types"
import { useState, useCallback } from "react"
import { root } from '@repo/core'
import { FileController } from "@repo/sdk"
import { useError } from "../data/use-error"
export const useFileUpload = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<ApiError | null>(null)
const [progress, setProgress] = useState(0)
const [uploadedUrl, setUploadedUrl] = useState<string | null>(null)
const uploadFile = useCallback(async (file: File | Blob, folder?: string) => {
setLoading(true)
setError(null)
setProgress(0)
setUploadedUrl(null)
try {
const formData = new FormData()
formData.append("file", file as any)
if (folder) {
formData.append("folder", folder)
}
const fileController = root.get(FileController)
const { data, error } = await useError(async () => await fileController.uploadS3(formData))
console.log({ data, error })
if (error) {
setError(error)
setLoading(false)
setProgress(0)
return { url: null, error }
}
if (data?.data) {
setUploadedUrl(data.data)
setProgress(100)
setLoading(false)
return { url: data.data, error: null }
}
setLoading(false)
setProgress(0)
return { url: null, error: { message: "上传失败" } as ApiError }
} catch (e) {
const err = e as ApiError
setError(err)
setLoading(false)
setProgress(0)
return { url: null, error: err }
}
}, [])
const reset = useCallback(() => {
setLoading(false)
setError(null)
setProgress(0)
setUploadedUrl(null)
}, [])
return {
loading,
error,
progress,
uploadedUrl,
uploadFile,
reset,
}
}