Giter VIP home page Giter VIP logo

axios-cache-adapter's Introduction

๐Ÿš€ axios-cache-adapter Build Status codecov bitHound Overall Score bitHound Dependencies

Caching adapter for axios

Adapted from superapi-cache by @stephanebachelier

Install

Using npm

npm install --save axios-cache-adapter

Or bower

bower install --save axios-cache-adapter

Or from a CDN like unpkg.com

<script type="text/javascript" src="https://unpkg.com/axios-cache-adapter"></script>

Usage

You can use the adapter directly

import axios from 'axios'
import { setupCache } from 'axios-cache-adapter'

const cache = setupCache({
  maxAge: 15 * 60 * 1000
})

const api = axios.create({
  adapter: cache.adapter
})

api({
  url: 'http://some-rest.api/url',
  method: 'get'
}).then(response => {
  // Do something fantastic with response.data \o/
  console.log('Request response:', response)

  // Interacting with the store, see `localForage` API.
  cache.store.length().then(length => {
    console.log('Cache store length:', length)
  })
})

Or you can get an instance of axios pre-configured with the cache adapter

import { setup } from 'axios-cache-adapter'

const api = setup({
  cache: {
    maxAge: 15 * 60 * 1000
  }
})

api({
  url: 'http://some-reset.api/url',
  method: 'get'
}).then(response => {
  // Do something awesome with response.data \o/
  console.log('Request response:', response)

  // Interacting with the store, see `localForage` API.
  api.cache.length().then(length => {
    console.log('Cache store length:', length)
  })
})

Custom localForage store example:

import localforage from 'localforage'
import memoryDriver from 'localforage-memoryStorageDriver'
import { setup } from 'axios-cache-adapter'

const store = localforage.createInstance({
  // List of drivers used
  driver: [
    localforage.INDEXEDDB,
    localforage.LOCALSTORAGE,
    memoryDriver
  ],
  // Prefix all storage keys to prevent conflicts
  name: 'my-cache'
})

const api = setup({
  cache: {
    maxAge: 15 * 60 * 1000,
    store
  }
})

api.get('http://some-reset.api/url').then(response => {
  // Display something beautiful with response.data ;)
})

API

setupCache(options)

Create a cache adapter instance. Takes an options object to configure how the cached requests will be handled, where they will be stored, etc.

Options

  • maxAge {Number}: Maximum time for storing each request in milliseconds, defaults to 15 minutes (15 * 60 * 1000)
  • limit {Number}: Maximum number of cached request (last in, first out queue system), no limit by default
  • store {Object}: An instance of localForage, defaults to a custom in memory store
  • key {Mixed}: Can either be a String or a Function which receives the request object as first parameter to return a unique cache key for each request. Defaults to req => req.url
  • exclude {Object}: Object defining which kind of requests should be excluded from cache
    • filter {Function}: A method which receives the request and returns true to exclude request from cache, defaults to null
    • query {Boolean}: If true all requests containing a query will be excluded, defaults to true
    • paths {Array}: An Array of regular expressions to match against request URLs, if a match is found it will be excluded, defaults to []
  • clearOnStale {Boolean}: Clear cached item when it is stale, defaults to true
  • clearOnError {Boolean}: Clear all cache when a write error occurs (prevents size quota problems with localStorage)
  • debug {Boolean}: Print some logs to console, defaults to false

Returns

setupCache() returns an object containing the configured adapter, the cache store and the config that is applied to this instance.

setup(options)

Create an axios instance pre-configured with the cache adapter. Takes an options object to configure the cache and axios at the same time.

Options

  • cache {Object}: Same options as the setupCache method

All the other parameters passed in the options will be passed directly to the axios.create method.

Returns

setup() returns an instance of axios pre-configured with the cache adapter. The cache store is conveniently attached to the axios instance as instance.cache for easy access.

Building

npm run build

Webpack is used to build umd versions of the library that are placed in the dist folder.

  • cache.js
  • cache.min.js
  • cache.bundled.js
  • cache.bundled.min.js

The bundled version contains all the dependencies necessary for axios-cache-adapter to work on its own.

axios-cache-adapter is developped in ES6 and uses async/await syntax. It is transpiled to ES5 using babel with the following presets and plugins:

Testing

Tests are executed using karma.

To launch a single run tests using ChromeHeadless:

npm test

To launch tests in watch mode in Chrome for easier debugging with devtools:

npm run watch

Browser vs Node.js

axios-cache-adapter was designed to run in the browser. It does work in nodejs using the in memory store. But storing data in memory is not the greatests idea ever.

You can give a store to override the in memory store but it has to comply with the localForage API and localForage does not work in nodejs for very good reasons that are better explained in this issue.

Maybe it should be possible to connect axios-cache-adapter to a redis store or something equivalent.

If you have any suggestions for a better way to work in nodejs please open an issue or submit a pull request.

License

MIT ยฉ Carl Ogren

axios-cache-adapter's People

Contributors

8ensmith avatar janbaykara avatar stephanebachelier avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.