Skip to content

Commit

Permalink
refactor: retry logic
Browse files Browse the repository at this point in the history
  • Loading branch information
typicode committed Dec 26, 2023
1 parent cc5b46b commit 7725ce5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 41 deletions.
32 changes: 0 additions & 32 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,5 @@
},
"engines": {
"node": ">=18"
},
"dependencies": {
"async-retry": "^1.3.3"
}
}
28 changes: 22 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,32 @@ import { rename, writeFile } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

import retry from 'async-retry'

// Returns a temporary file
// Example: for /some/file will return /some/.file.tmp
function getTempFilename(file: PathLike): string {
const f = file instanceof URL ? fileURLToPath(file) : file.toString()
return join(dirname(f), `.${basename(f)}.tmp`)
}

// Retries an asynchronous operation with a delay between retries and a maximum retry count
async function retryAsyncOperation(
fn: () => Promise<void>,
maxRetries: number,
delayMs: number,
): Promise<void> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error) {
if (i < maxRetries - 1) {
await new Promise((resolve) => setTimeout(resolve, delayMs))
} else {
throw error // Rethrow the error if max retries reached
}
}
}
}

type Resolve = () => void
type Reject = (error: Error) => void
type Data = Parameters<typeof writeFile>[1]
Expand Down Expand Up @@ -48,13 +65,12 @@ export class Writer {
try {
// Atomic write
await writeFile(this.#tempFilename, data, 'utf-8')
await retry(
await retryAsyncOperation(
async () => {
await rename(this.#tempFilename, this.#filename)
},
{
minTimeout: 100,
},
10,
100,
)

// Call resolve
Expand Down

0 comments on commit 7725ce5

Please sign in to comment.