Axios: Tambahkan dukungan untuk caching permintaan GET

Dibuat pada 11 Des 2014  ·  18Komentar  ·  Sumber: axios/axios

Akan diimplementasikan menggunakan https://github.com/mzabriskie/felix

Komentar yang paling membantu

Saya telah membuat satu set ekstensi untuk axios, termasuk caching permintaan GET, yang tergantung pada mekanisme adaptor kustom axios dan lru-cache, dan yang paling penting adalah cakupan pengujian telah mencapai 100% . https://github.com/kuitos/axios-extensions

Contoh

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // cache will be enabled by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked

btw, saya telah membuat ekstensi kuat lainnya, yang dapat membatasi permintaan dalam waktu ambang.

import axios from 'axios';
import { throttleAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    adapter: throttleAdapterEnhancer(axios.defaults.adapter, 2 * 1000)
});

http.get('/users'); // make real http request
http.get('/users'); // responsed from the cache
http.get('/users'); // responsed from the cache

untuk informasi lebih lanjut, Anda dapat memeriksa dokumen api

Semoga dapat bermanfaat bagi Anda dan jangan ragu untuk mengajukan pertanyaan🙂

Semua 18 komentar

Heh, aku baru saja melihat ini! Saya pikir pencegat dapat digunakan atau transformator yang akan segera menyelesaikan dengan respons, tetapi belum beruntung.

Felix terlihat menarik tentunya...

:+1: Versi simpul tidak terlalu berguna bagi saya sampai kami memiliki lapisan caching yang dapat dicolokkan.

Ada kemajuan di browser? Cache berfungsi?

Bump... perlu ini atau saya akan menukar axios dengan superagent atau meminta aplikasi produksi kami... menyebabkan perlambatan besar

@mzabriskie Saya telah menambahkan dukungan untuk ttls di mzabriskie/felix#4 dan dapat mengatasi ini jika Anda menyukai implementasi saya di sana.

Senang melihat masalah ini dihidupkan kembali, itu akan menyelamatkan saya dari keharusan menulis banyak boilerplate :smile:

Saya pikir saat ini caching dapat diimplementasikan melalui interseptor, meskipun tidak terlalu bersih:

cache(axios, options);

function cache(instance, options) {
  instance.interceptors.request.use(function(config) {
    if (!config.method === 'get') {
      return config;
    }
    return cache.get(generateOptions(config, options))
      .then(createCachedError, function() { return config; });
  });
  instance.interceptors.response.use(null, function(error) {
    if (error.cachedResult) {
      return Promise.resolve(error.cachedResult);
    }
    return Promise.reject(error);
  });
}

Cara yang lebih bersih untuk melakukan ini adalah dengan mendefinisikan adaptor default (http, xhr) di instance default dan kemudian menggunakan adaptor khusus seperti ini:

axios.get('url', { adapter: cachingAdapter });

function cachingAdapter(resolve, reject, config) {
  cache.get(generateOptions(config, options)).then(function(result) {
    resolve(createResponse(result));
  }, function() {
    axios.defaults.adapter(resolve, reject, config);
  });
}

Saya juga berpikir bahwa adaptor harus mengembalikan janji alih-alih mendapatkan metode penyelesaian dan penolakan, tetapi itu bukan masalah saat ini.

Saya pikir Axios harus meninggalkan caching di luar inti dan mengizinkan implementasi seperti ini.

Bagaimana menurutmu?

Saya menutup masalah ini karena tidak aktif. Jangan ragu untuk membukanya kembali jika Anda menganggapnya perlu diskusi lebih lanjut;)

Apakah ada solusi untuk ini? Tampaknya aneh bahwa tidak ada cara yang jelas untuk permintaan caching ...

@rubennorte apa itu opsi dalam cache (aksios, opsi); ?

@john1jan opsi hipotetis untuk klien cache yang Anda gunakan. Misalnya, opsi untuk klien catbox .

Bergantung pada kasus penggunaan Anda, Anda bisa mengganti fungsi get :

// Create intercepting get function which returns cached promise,
// hence multiple requests to the same URL will be resolved by
// a single promise.
function cachingGet (get) {
  const cache = new Map()

  return function cachedGet (url) {
    const key = url

    if (cache.has(key)) {
      return cache.get(key)
    } else {
      const request = get(...arguments)
      cache.set(key, request)
      return request
    }
  }
}

const instance = axios.create(config)
instance.get = cachingGet(instance.get)

mungkin solusi yang lebih baik akan menggunakan pola adpater?

Buat sesuatu untuk ini https://github.com/RasCarlito/axios-cache-adapter :)
Saya merilis versi pertama tetapi perlu lebih banyak pengujian. Semoga bisa bermanfaat untuk orang lain.
Saya akan menerapkannya dalam proyek besar untuk salah satu klien saya.

Secara default, ia menggunakan penyimpanan khusus dalam memori untuk cache.
Di browser ia dapat menerima instance localStorage Dijanjikan seperti localForage .
Saya belum menjelajahi solusi yang setara di Node.js.

Contoh:

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

const cache = setupCache(/* options */)
const api = axios.create({
  adapter: cache.adapter
})

api.get('some-url').then(response => /* Do something awesome with response.data \o/ */)

salam :bir:

Saya telah membuat satu set ekstensi untuk axios, termasuk caching permintaan GET, yang tergantung pada mekanisme adaptor kustom axios dan lru-cache, dan yang paling penting adalah cakupan pengujian telah mencapai 100% . https://github.com/kuitos/axios-extensions

Contoh

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // cache will be enabled by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked

btw, saya telah membuat ekstensi kuat lainnya, yang dapat membatasi permintaan dalam waktu ambang.

import axios from 'axios';
import { throttleAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    adapter: throttleAdapterEnhancer(axios.defaults.adapter, 2 * 1000)
});

http.get('/users'); // make real http request
http.get('/users'); // responsed from the cache
http.get('/users'); // responsed from the cache

untuk informasi lebih lanjut, Anda dapat memeriksa dokumen api

Semoga dapat bermanfaat bagi Anda dan jangan ragu untuk mengajukan pertanyaan🙂

Untuk orang yang hanya ingin menonaktifkan cache, saya menggunakan:
const config = { headers: {'Content-Type': 'application/json','Cache-Control' : 'no-cache'}};
dan panggil api saya seperti ini:
const { data } = await axios.get('http://www.youraddress.com/api/data.json', config);

Bagaimana dengan ini di TypeScript [dapat dengan mudah menjadi hal JS] -

export class AxiosFactory {

    private static CACHE_MAP = new Map<string, AxiosResponse>();

    private static attachTokenToURL(config): AxiosFactory {
        let urlToUse = config.url;
        // Custom Token Attachment
        return config;
    }

    private static cachingAdapter(config: AxiosRequestConfig): AxiosPromise<AxiosResponse<any>> {
        if (!!AxiosFactory.CACHE_MAP.get(config.url)) {
            return new Promise((resolve, reject) => {
                resolve(AxiosFactory.CACHE_MAP.get(config.url));
            });
        } else {
            return axios.defaults.adapter(config);
        }
    }

    static GetAxiosConfig(baseUrl, enableCaching = false) {
        let defaultConfig = {
            baseURL: baseUrl,
            headers: { "Authorization": TokenService.GetTokenValue() } //optional
        } as AxiosRequestConfig;

        if (enableCaching) {
            defaultConfig.adapter = AxiosFactory.cachingAdapter
        }
        const instance = axios.create(defaultConfig);

        // Only for Adding Tokens in here.
        instance.interceptors.request.use((config) => {
            config = AxiosFactory.attachTokenToURL(config);
            return config;
        }, (error) => {
            return Promise.reject(error);
        });

        // Only for catching Caches
        instance.interceptors.response.use((response) => {
            AxiosFactory.CACHE_MAP.set(response.request.responseURL, response);
            return response;
        }, (error) => {
            return Promise.reject(error);
        });

        return instance;
    }
}

const config = { headers: {'Content-Type': 'application/json','Cache-Control' : 'no-cache'}};

URL Permintaan: http://myurl
Kebijakan Perujuk: tidak ada perujuk-saat-downgrade
Header sementara ditampilkan
Terima: aplikasi/json, teks/polos, /
ApiKey: myapikey
Kontrol Cache: tanpa cache
Referer: http://localhost :3000/orders
Agen-Pengguna: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, seperti Gecko) Chrome/81.0.4044.113 Safari/537.36

itu menyebabkan masalah saat meminta 'Cache-Control': 'no-cache' di header .
bagaimana saya bisa menerapkan kontrol-cache di instance axios saya.

Kode saya:

const contoh = axios.create({baseURL: url});

instance.defaults.headers['ApiKey'] = kunci;
instance.defaults.headers['Cache-Control'] = "tanpa cache";

Saya juga telah mencoba solusi Anda lewat konfigurasi dalam satu permintaan. tapi tidak beruntung.

apa yang akan menjadi solusinya?

Apakah halaman ini membantu?
0 / 5 - 0 peringkat