Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Axios client initial #10

Merged
merged 2 commits into from
Apr 21, 2022
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
5 changes: 5 additions & 0 deletions .changeset/rude-carrots-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gradientedge/axios-client': minor
---

Initial cut of axios-client package
40 changes: 40 additions & 0 deletions packages/axios-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# `@gradientedge/axios-client`

A simple factory function for creating an axios client for use in a nodejs environment. No
options are required when calling the `getAxiosClient` function. In this case, default values
will be used for the retry and HttpsAgent config.

Note that no `HttpAgent` config is provided. We expect all requests to be made via SSL and
therefore the only agent we care about is `HttpsAgent`.

Minimal example:
```typescript
import { getAxiosClient } from '@gradientedge/axios-client'

/**
* No options provided, so this will use the default retry and HttpsAgent configuration.
*/
const client = getAxiosClient()
```

Full config override example:
```typescript
import { getAxiosClient } from '@gradientedge/axios-client'

const client = getAxiosClient({
httpsAgent: {
keepAlive: false,
timeout: 10000,
maxSockets: 40,
scheduling: 'lifo',

},
retry: {
delayMs: 100,
maxRetries: 5,
}
})
```

The `client` variable above is an [AxiosInstance](https://github.com/axios/axios/blob/master/index.d.ts#L235)
which gives you access to all the standard axios methods and functionality.
10 changes: 10 additions & 0 deletions packages/axios-client/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export default {
preset: 'ts-jest',
testEnvironment: 'node',
verbose: true,
passWithNoTests: true,
rootDir: '.',
testMatch: ['**/__tests__/**/*.test.ts'],
testPathIgnorePatterns: ['node_modules/', 'dist/'],
setupFilesAfterEnv: ['jest-extended/all'],
}
33 changes: 33 additions & 0 deletions packages/axios-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@gradientedge/axios-client",
"version": "0.0.0",
"description": "Factory for creating an axios client object with built-in default keep-alive/retry mechanism",
"author": "Jimmy Thomson <[email protected]>",
"homepage": "https://github.com/gradientedge/common-utils#readme",
"license": "ISC",
"main": "dist/index",
"types": "dist/index",
"files": [
"dist",
"!dist/**/__tests__"
],
"repository": {
"type": "git",
"url": "https://github.com/gradientedge/common-utils.git"
},
"scripts": {
"clean": "rimraf dist && rm -f tsconfig.tsbuildinfo",
"build": "tsc --build",
"build:watch": "tsc --build --incremental --watch",
"test": "pnpm test --workspace --filter @gradientedge/common-utils"
},
"bugs": {
"url": "https://github.com/gradientedge/common-utils/issues"
},
"dependencies": {
"axios": "^0.26.1",
"axios-retry": "^3.2.4",
"agentkeepalive": "^4.2.1"
},
"devDependencies": {}
}
14 changes: 14 additions & 0 deletions packages/axios-client/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { RetryConfig } from './types'
import { HttpsOptions } from 'agentkeepalive'

export const DEFAULT_RETRY_CONFIG: RetryConfig = {
delayMs: 20,
maxRetries: 3,
}

export const DEFAULT_AGENT_CONFIG: HttpsOptions = {
keepAlive: true,
timeout: 5000,
maxSockets: 20,
scheduling: 'fifo',
}
49 changes: 49 additions & 0 deletions packages/axios-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { HttpsAgent } from 'agentkeepalive'
import axios, { AxiosError } from 'axios'
import axiosRetry, { isNetworkOrIdempotentRequestError } from 'axios-retry'
import { RequestConfig } from './types'
import { DEFAULT_AGENT_CONFIG, DEFAULT_RETRY_CONFIG } from './constants'

/**
* Get an axios instance configured with the given retry mechanism
* and custom agent for socket re-use.
*/
export function getAxiosClient(options?: RequestConfig) {
const retry = options?.retry || DEFAULT_RETRY_CONFIG
const httpsAgent = new HttpsAgent({
...DEFAULT_AGENT_CONFIG,
...options?.httpsAgent,
})
const client = axios.create({
httpsAgent,
timeout: httpsAgent.options.timeout,
})

if (retry.maxRetries) {
axiosRetry(client, {
retries: retry.maxRetries,
retryDelay: getCalculateRetryDelayFn(retry.delayMs),
shouldResetTimeout: true,
retryCondition: function (error: AxiosError) {
// The error code for a timeout is ECONNABORTED. Default axios-retry
// behaviour doesn't consider timeouts 'retryable'.
return isRequestRetryable(error)
},
})
}

return client
}

export function getCalculateRetryDelayFn(delayMs: number) {
return (retryCount: number) => {
if (retryCount === 0) {
return 0
}
return delayMs * 2 ** (retryCount - 1)
Copy link

@jameswiltshire jameswiltshire Apr 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should have jitter support in here too - here's snippet adding that (arguably should be +/- to normalise the jitter distribution both sides of retryDelay - but this is fine to add the randomness)
const delay = RETRY_DELAY_MS * 2 ** (retryCount - 1) + _.random(0, RETRY_JITTER_MS) // exponential backoff with jitter

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an open issue in the axios-retry package to add this there directly 😄
JustinBeckwith/retry-axios#172

}
}

export function isRequestRetryable(error: AxiosError) {
return isNetworkOrIdempotentRequestError(error) || (!error.response && error.code === 'ECONNABORTED')
}
11 changes: 11 additions & 0 deletions packages/axios-client/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { AgentOptions } from 'https'

export interface RequestConfig {
httpsAgent: AgentOptions
retry: RetryConfig
}

export interface RetryConfig {
maxRetries: number
delayMs: number
}
10 changes: 10 additions & 0 deletions packages/axios-client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
66 changes: 62 additions & 4 deletions pnpm-lock.yaml

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