How to use axios-cache-adapter - 9 common examples

To help you get started, we’ve selected a few axios-cache-adapter examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github topheman / npm-registry-browser / src / services / ApiManager.js View on Github external
constructor(key, config) {
    // extract any non-axios-specific config (like cache mode, mock mode ...)
    const {
      isCacheEnabled,
      mocks,
      makeMockedClient,
      preprocessMocking,
      ...axiosConfig
    } = makeConfig(key, config);
    if (!instance[key]) {
      instance[key] = decorate(key, this);
      if (isCacheEnabled) {
        this.cache = setupCache({ maxAge: 15 * 60 * 1000 });
        axiosConfig.adapter = this.cache.adapter;
        if (process.env.NODE_ENV === "development") {
          console.info(`[ApiManager](${key}) Cache is enabled`, this.cache);
        }
      }
      if (mocks) {
        console.warn(
          `[ApiManager](${key}) Mocking API. Requests will be intercepted and served. The files containing the mocks are in src/services/mocks. To generate those files, run: npm run record-http-mocks.`
        );
        console.warn(
          `[ApiManager](${key}) Unmocked requests will pass through and will be logged.`
        );
        this.client = makeMockedClient(axiosConfig, mocks, {
          preprocessMocking
        });
      } else {
github remotejobsbr / remote-jobs-client / utils / githubAPI.js View on Github external
import axios from 'axios'
import { setupCache } from 'axios-cache-adapter'

const cache = setupCache({
  maxAge: 3 * 60 * 1000 // Three minutes
})

const instance = axios.create({
  adapter: cache.adapter,
  baseURL: 'https://gcq2gnybeb.execute-api.us-east-1.amazonaws.com/dev'
})

export const fetchJobsByCategory = category =>
  instance.get(`/github/jobs/${category}`).then(res => res.data)

export const fetchJob = (ownerName, issueNumber) =>
  instance
    .get(`/github/jobs/repository/${ownerName}/${issueNumber}`)
    .then(res => res.data)
github haoict / production-ready-webapp-boilerplate / src / services / utils / index.js View on Github external
import axios from 'axios';
import envConfig from '../../config/env-config';
import { setupCache } from 'axios-cache-adapter';

let apiUrl;
if (process.browser) {
  // in client side, we don't have dotEnv config, so we have to set apiUrl
  // in window object and get it here
  apiUrl = window.apiUrl;
} else {
  apiUrl = envConfig.app.apiUrl;
}

// Create `axios-cache-adapter` instance
const cache = setupCache({ maxAge: 15 * 60 * 100, exclude: { query: false } });
const noCache = setupCache({ maxAge: 0 });

const createAxiosInstance = (path, disableCache) => {
  return axios.create({
    baseURL: apiUrl + path,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    timeout: 9000,
    adapter: disableCache ? noCache.adapter : cache.adapter
  });
};

export async function fetchApi(path, pathParam, query = null, disableCache = false) {
  // always disable cache if request doesn't come from client-side
github haoict / production-ready-webapp-boilerplate / src / services / utils / index.js View on Github external
import axios from 'axios';
import envConfig from '../../config/env-config';
import { setupCache } from 'axios-cache-adapter';

let apiUrl;
if (process.browser) {
  // in client side, we don't have dotEnv config, so we have to set apiUrl
  // in window object and get it here
  apiUrl = window.apiUrl;
} else {
  apiUrl = envConfig.app.apiUrl;
}

// Create `axios-cache-adapter` instance
const cache = setupCache({ maxAge: 15 * 60 * 100, exclude: { query: false } });
const noCache = setupCache({ maxAge: 0 });

const createAxiosInstance = (path, disableCache) => {
  return axios.create({
    baseURL: apiUrl + path,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    timeout: 9000,
    adapter: disableCache ? noCache.adapter : cache.adapter
  });
};

export async function fetchApi(path, pathParam, query = null, disableCache = false) {
  // always disable cache if request doesn't come from client-side
  if (!process.browser) disableCache = true;
github RasCarlito / axios-cache-adapter / examples / basic.js View on Github external
const {setup} = require('axios-cache-adapter')

// Create an `axios` instance with `axios-cache-adapter` pre-configured
const api = setup({
    // `axios` options
    baseURL: 'https://httpbin.org',

    // `axios-cache-adapter` options
    cache: {
        // Cache expiration in milliseconds, here 15min
        maxAge: 15 * 60 * 1000,
        // Cache exclusion rules
        exclude: {
            // Store responses from requests with query parameters in cache
            query: false
        }
    }
})

// Make a request to https://httpbin.org/get?foo=bar (runkit handles what appears to be a top-level await)
github zenghongtu / Remu / src / utils.ts View on Github external
import Axios from 'axios';
import { Modal, notification, message } from 'antd';
import { setupCache, setup } from 'axios-cache-adapter';
import localforage from 'localforage';

const baseURL = 'https://api.github.com';

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

export const request = setup({
  baseURL,
  cache: {
    maxAge: 60 * 60 * 1000,
    exclude: { query: false },
    store: forageStore,
    invalidate: async (config, request) => {
      if (request.clearCacheEntry) {
        // @ts-ignore
        await config.store.removeItem(config.uuid);
      }
    },
    readOnError: (error, request) => {
      return (
        !error.response ||
        (error.response.status >= 500 && error.response.status < 600)
      );
github beaverbuilder / assistant / src / system / utils / wordpress / cache-helper.js View on Github external
generateCacheAdapter() {
		this.cacheConfig.store = this.cacheStore
		this.cacheConfig.key = this.generateCacheKey
		this.cacheConfig.invalidate = this.shouldInvalidate

		let cache = setupCache( this.cacheConfig )
		return cache.adapter
	}
}
github beaverbuilder / assistant / src / system / utils / wordpress / rest.js View on Github external
import Promise from 'promise'
import axios from 'axios'
import { setupCache } from 'axios-cache-adapter'
import qs from 'qs'

const { apiRoot, nonce } = FL_ASSISTANT_CONFIG

/**
 * Cache adapter for axios requests.
 *
 * @type {Object}
 */
const cache = setupCache( {
	debug: false,
	maxAge: 15 * 60 * 1000,
	exclude: {
		query: false,
	},
	key: ( req ) => {
		let key = req.url + qs.stringify( req.params, { addQueryPrefix: true } )
		if ( req.cacheKey ) {
			return `fl-cache-${ req.cacheKey }-${ key }`
		}
		return key
	},
	invalidate: ( config, req ) => {
		const method = req.method.toLowerCase()
		if ( req.cacheKey && 'get' !== method ) {
			config.store.iterate( ( data, key ) => {
github PeteAndersen / swarfarm / frontend / src / services / api.js View on Github external
import { setup } from "axios-cache-adapter";

const apiRoot =
  process.env.NODE_ENV === "development"
    ? "http://127.0.0.1:8000/api/v2"
    : "https://swarfarm.com/api/v2";

const api = setup({
  baseURL: apiRoot,
  withCredentials: true,
  cache: {
    maxAge: 15 * 60 * 1000,
    exclude: {
      query: false,
      filter: config => config.url.startsWith("/profiles"),
    },
  },
});

if (process.env.NODE_ENV === "development") {
  api.interceptors.response.use(
    function(response) {
      const params = response.config.params
        ? Object.keys(response.config.params)

axios-cache-adapter

Caching adapter for axios

MIT
Latest version published 3 years ago

Package Health Score

53 / 100
Full package analysis

Popular axios-cache-adapter functions