Skip to content

Commit

Permalink
fix: don't sleep after the last retry attempt (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
CahidArda authored Nov 6, 2024
1 parent 6d1c549 commit b4fd76d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
29 changes: 29 additions & 0 deletions src/http/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,32 @@ describe("Abort", () => {
expect(bodyResponse.result).toEqual("Abort works!");
});
});

describe.only("retry", () => {
test("should terminate after sleeping 5 times", async () => {
// init a cient which will always get errors
const client = newHttpClient(
{
retries: 5,
backoff: (retryCount) => Math.exp(retryCount) * 50,
},
{
url: "",
token: "non-existent",
}
);

// get should take 4.287 seconds and terminate before the timeout.
const throws = () =>
Promise.race([
client.request({
path: ["upsert"],
body: "wrong-body",
}),
new Promise((r) => setTimeout(r, 4500)),
]);

// if the Promise.race doesn't throw, that means the retries took longer than 4.5s
expect(throws).toThrow("fetch() URL is invalid");
});
});
4 changes: 3 additions & 1 deletion src/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ export class HttpClient implements Requester {
break;
}
error = error_ as Error;
await new Promise((r) => setTimeout(r, this.retry.backoff(i)));
if (i < this.retry.attempts) {
await new Promise((r) => setTimeout(r, this.retry.backoff(i)));
}
}
}
if (!res) {
Expand Down

0 comments on commit b4fd76d

Please sign in to comment.