|
| 1 | +import { useQueryClient } from '@tanstack/react-query' |
| 2 | +import { API_ROUTES, SUCCESS_TIMEOUT } from 'data-services/constants' |
| 3 | +import { useState } from 'react' |
| 4 | +import { useUploadCapture } from './useUploadCapture' |
| 5 | + |
| 6 | +type Result = PromiseSettledResult<any> |
| 7 | + |
| 8 | +const isRejected = (result: Result) => result.status === 'rejected' |
| 9 | + |
| 10 | +export const useUploadCaptures = (onSuccess?: () => void) => { |
| 11 | + const queryClient = useQueryClient() |
| 12 | + const [results, setResults] = useState<Result[]>() |
| 13 | + const { uploadCapture, isLoading, isSuccess, reset } = useUploadCapture( |
| 14 | + () => { |
| 15 | + setTimeout(() => { |
| 16 | + reset() |
| 17 | + }, SUCCESS_TIMEOUT) |
| 18 | + } |
| 19 | + ) |
| 20 | + |
| 21 | + const error = results?.some(isRejected) |
| 22 | + ? 'Not all images could not be uploaded, please retry.' |
| 23 | + : undefined |
| 24 | + |
| 25 | + return { |
| 26 | + isLoading, |
| 27 | + isSuccess, |
| 28 | + error, |
| 29 | + uploadCaptures: async (params: { |
| 30 | + projectId: string |
| 31 | + deploymentId: string |
| 32 | + files: File[] |
| 33 | + }) => { |
| 34 | + const promises = params.files |
| 35 | + .filter((_, index) => { |
| 36 | + if (error) { |
| 37 | + // Only retry rejected requests |
| 38 | + return results?.[index]?.status === 'rejected' |
| 39 | + } |
| 40 | + |
| 41 | + return true |
| 42 | + }) |
| 43 | + .map((file) => |
| 44 | + uploadCapture({ |
| 45 | + projectId: params.projectId, |
| 46 | + deploymentId: params.deploymentId, |
| 47 | + file, |
| 48 | + }) |
| 49 | + ) |
| 50 | + |
| 51 | + setResults(undefined) |
| 52 | + const updatesResults = await Promise.allSettled(promises) |
| 53 | + setResults(updatesResults) |
| 54 | + |
| 55 | + if (!updatesResults?.some(isRejected)) { |
| 56 | + queryClient.invalidateQueries([API_ROUTES.CAPTURES]) |
| 57 | + queryClient.invalidateQueries([API_ROUTES.DEPLOYMENTS]) |
| 58 | + queryClient.invalidateQueries([API_ROUTES.SUMMARY]) |
| 59 | + queryClient.invalidateQueries([API_ROUTES.PROJECTS, params.projectId]) |
| 60 | + onSuccess?.() |
| 61 | + } |
| 62 | + }, |
| 63 | + } |
| 64 | +} |
0 commit comments