Parcourir la source

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

GitOrigin-RevId: b30895061ee6fdfb6488d27ce2f91d4e410735aa
M Fahru il y a 3 ans
Parent
commit
9e5aabea33

+ 6 - 2
services/web/frontend/js/features/history/context/hooks/use-restore-deleted-file.ts

@@ -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)

+ 33 - 0
services/web/frontend/js/features/history/utils/wait-for.ts

@@ -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()
+  })
+}