Skip to content

stephenhebert/axios-plugins

Repository files navigation

@stephenhebert/axios-plugins

A collection of Axios plugins for enhanced functionality.

Features

  • Allow 404 Responses: Handle 404 responses gracefully without throwing errors.
  • Inflight Cache: Prevent duplicate requests by caching inflight requests.
  • Get All Pages: Automatically fetch paginated API results.

Installation

Install the package via npm:

npm install @stephenhebert/axios-plugins

Usage

Allow 404 Responses

Enable the allow404 plugin to handle 404 responses gracefully:

import axios from 'axios'
import { allow404 } from '@stephenhebert/axios-plugins'

const client = axios.create({
  plugins: {
    allow404: true,
  },
})

allow404.install(client)

client.get('http://example.com/api/data')
  .then(response => console.log(response.status)) // 404
  .catch(error => console.error(error))

Inflight Cache

Prevent duplicate requests by enabling the inflightCache plugin:

import axios from 'axios'
import { inflightCache } from '@stephenhebert/axios-plugins'

const client = axios.create({
  plugins: {
    inflightCache: true,
  },
})

inflightCache.install(client)

client.get('http://example.com/api/data')
  .then(response => console.log(response.data))

Get All Pages

Automatically fetch all paginated results:

import axios from 'axios'
import { getAllPages } from '@stephenhebert/axios-plugins'

const client = axios.create()

getAllPages.install(client)

client.get('http://example.com/api/data', {
    plugins: {
      getAllPages: true,
    },
  })
  .then(response => console.log(response.data))

With Abort Controller

Wrap request callback in factory decorator to handle aborting previous requests when subsequent requests are made:

import axios from 'axios'
import { withAbortController } from '@stephenhebert/axios-plugins'

const client = axios.create()

const fetchData = withAbortController( async (signal) => { 
  try {
    await client.get('http://example.com/api/data', { signal } )
  }
  catch (error) {}
})

fetchData() // starts first request
fetchData() // cancels first request and starts second request

Development

Build

Run the following command to build the project:

npm run build

Test

Run the tests using Vitest:

npm run test

Lint

Lint the codebase using ESLint:

npm run lint

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

Keywords

  • axios
  • plugins
  • middleware
  • interceptors
  • http
  • typescript
  • javascript
  • api