Implement auto retry mechanism for deleted file restore in history react (#12866)

GitOrigin-RevId: b30895061ee6fdfb6488d27ce2f91d4e410735aa
This commit is contained in:
M Fahru 2023-05-02 07:06:04 -07:00 committed by Copybot
parent 1fb921de99
commit 9e5aabea33
2 changed files with 39 additions and 2 deletions

View file

@ -4,6 +4,7 @@ import { useLayoutContext } from '../../../../shared/context/layout-context'
import useAsync from '../../../../shared/hooks/use-async'
import { restoreFile } from '../../services/api'
import { isFileRemoved } from '../../utils/file-diff'
import { waitFor } from '../../utils/wait-for'
import { useHistoryContext } from '../history-context'
import type { HistoryContextValue } from '../types/history-context-value'
@ -22,10 +23,13 @@ export function useRestoreDeletedFile() {
await runAsync(
restoreFile(projectId, selectedFile)
.then(data => {
.then(async data => {
const { id, type } = data
const entity = ide.fileTreeManager.findEntityById(id)
const entity = await waitFor(
() => ide.fileTreeManager.findEntityById(id),
3000
)
if (type === 'doc') {
ide.editorManager.openDoc(entity)

View file

@ -0,0 +1,33 @@
export function waitFor<T>(
testFunction: () => T,
timeout: number,
pollInterval = 500
): Promise<T> {
const iterationLimit = Math.floor(timeout / pollInterval)
let iterations = 0
return new Promise<T>((resolve, reject) => {
const tryIteration = () => {
if (iterations > iterationLimit) {
reject(
console.error(
`waiting too long, ${JSON.stringify({ timeout, pollInterval })}`
)
)
return
}
iterations += 1
const result = testFunction()
if (result) {
resolve(result)
return
}
setTimeout(tryIteration, pollInterval)
}
tryIteration()
})
}