Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Feature: Implement retries mechanism #11

Merged
merged 2 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@
"dependencies": {
"axios": "^1.6.2",
"http-cookie-agent": "^5.0.4",
"retry": "^0.13.1",
"tough-cookie": "^4.1.3"
},
"devDependencies": {
"@types/jest": "^29.5.11",
"@types/node": "^14.14.31",
"@types/retry": "^0.12.5",
"@types/tough-cookie": "^4.0.5",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
Expand Down
75 changes: 65 additions & 10 deletions src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe('Client', () => {
url: 'https://api.swell.store',
verifyCert: true,
version: 1,
retries: 0,
});
});

Expand All @@ -63,6 +64,7 @@ describe('Client', () => {
url: 'https://api.swell.store',
verifyCert: false,
version: 2,
retries: 0,
});
});

Expand Down Expand Up @@ -141,11 +143,7 @@ describe('Client', () => {

mock.onPost('/products').reply(200, 'result');

const response = await client.request(
HttpMethod.post,
'/products',
{},
);
const response = await client.request(HttpMethod.post, '/products', {});

expect(response).toEqual('result');
});
Expand All @@ -155,11 +153,9 @@ describe('Client', () => {

mock.onPut('/products/{id}').reply(200, 'result');

const response = await client.request(
HttpMethod.put,
'/products/{id}',
{ id: 'foo' },
);
const response = await client.request(HttpMethod.put, '/products/{id}', {
id: 'foo',
});

expect(response).toEqual('result');
});
Expand Down Expand Up @@ -198,4 +194,63 @@ describe('Client', () => {
).rejects.toThrow(new Error('timeout of 0ms exceeded'));
});
}); // describe: #request

describe('#retry', () => {
test('handle zero retries by default', async () => {
const client = new Client('id', 'key');

// Simulate server failure on first 2 attempts and success on the third
let retryCounter = 0;
DimaZhukovsky marked this conversation as resolved.
Show resolved Hide resolved
mock.onGet('/products/:count').reply(() => {
retryCounter++;
if (retryCounter < 2) {
throw new Error('Internal Server Error');
}
return [200, 42];
});

await expect(
client.request(HttpMethod.get, '/products/:count', {}),
).rejects.toThrow(new Error('Internal Server Error'));
});

test('handle retries option', async () => {
const client = new Client('id', 'key', { retries: 3 });

// Simulate server failure on first 2 attempts and success on the third
let retryCounter = 0;
mock.onGet('/products/:count').reply(() => {
retryCounter++;
if (retryCounter < 2) {
throw new Error('Internal Server Error');
}
return [200, 42];
});

const response = await client.request(
HttpMethod.get,
'/products/:count',
{},
);
expect(response).toEqual(42);
});

test('handle return error if response not received after retries', async () => {
const client = new Client('id', 'key', { retries: 3 });

// Simulate server failure on first 4 attempts and success on the fifth
let retryCounter = 0;
mock.onGet('/products/:count').reply(() => {
retryCounter++;
if (retryCounter < 5) {
throw new Error('Internal Server Error');
}
return [200, 42];
});

await expect(
client.request(HttpMethod.get, '/products/:count', {}),
).rejects.toThrow(new Error('Internal Server Error'));
});
}); // describe: #retry
});
42 changes: 30 additions & 12 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as axios from 'axios';
import * as retry from 'retry';
import { CookieJar } from 'tough-cookie';
import { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/http';

Expand All @@ -19,6 +20,7 @@ export interface ClientOptions {
version?: number;
timeout?: number;
headers?: HttpHeaders;
retries?: number;
}

const MODULE_VERSION: string = (({ name, version }) => {
Expand All @@ -35,6 +37,7 @@ const DEFAULT_OPTIONS: Readonly<ClientOptions> = Object.freeze({
verifyCert: true,
version: 1,
headers: {},
retries: 0, // 0 => no retries
});

class ApiError extends Error {
Expand Down Expand Up @@ -163,21 +166,36 @@ export class Client {
url: string,
data?: unknown,
): Promise<T> {
if (this.httpClient === null) {
throw new Error('Swell API client not initialized');
}

// Prepare url and data for request
const requestParams = transformRequest(method, url, data);

let response;
try {
response = await this.httpClient.request<T>(requestParams);
} catch (error) {
throw transformError(error);
}

return transformResponse(response).data;
return new Promise((resolve, reject) => {
const { retries } = this.options;

const operation = retry.operation({
retries,
minTimeout: 20,
maxTimeout: 100,
factor: 1,
randomize: false,
});

operation.attempt(async () => {
if (this.httpClient === null) {
return reject(new Error('Swell API client not initialized'));
}

try {
const response = await this.httpClient.request<T>(requestParams);
resolve(transformResponse(response).data);
} catch (error) {
if (operation.retry(error as Error)) {
return;
}
reject(transformError(operation.mainError()));
}
});
});
}
}

Expand Down
Loading