Skip to main content
Version: 3.9.x

Browser caching

You can define cache strategy for each request individually. This feature is using The Cache Storage Api

Define cache params

import { RestRequest, IResponse } from "@mihanizm56/fetch-api";

export const getWhateverRequest = (someData): Promise<IResponse> =>
  new RestRequest().getRequest({
    endpoint: "http://localhost:3000",
    // here we define params for browser caching
    browserCacheParams: {
      strategy: 'StaleWhileRevalidate',
      requestCacheKey: `some request cache key`,
      storageCacheName: `some storage name`,
      expires: 1000 * 60 * 60 * 24 * 365, // 1 year,
      debug: true,
    },
  });

Cache strategies

You can read about strategies here but you should understand that we have a fetch-api library instead of a service worker in the scheme

CacheFirst

  • If found not expired value in cache - then return it
  • Make request and save to cache if expired or not exists

StaleWhileRevalidate

  • If found not expired value in cache - then return it
  • And after return from cache - make request and update cache

NetworkFirst

  • Always make the request
  • If error - try to get from cache if not expires
  • If success - update the cache
  • If timeout provided - after timeout tries to take cached value

Parameters

NameTypeComments
disabledCachebooleandisabled cache
strategyNetworkFirst, StaleWhileRevalidate, CacheFirstcache strategy for the request
requestCacheKeystringmain request cache key
storageCacheNamestringmain request storage key
expiresnumbercache time in ms
expiresToDatenumbercache time to determined date
timeoutnumbertimeout for request - if it is out - the cached previos result will be given (only NetworkFirst strategy has this feature)
onUpdateCachefunctioncallback is called if cache was updated
onRequestErrorfunctioncallback is called if the request has an error
debugbooleanflag for logging in the browser developer tools
onCacheHitfunctioncallback is called when cache hit
onCacheMissfunctioncallback is called when cache miss
minAllowedQuotanumbermin request cache allowed quota in cache-storage

Example with a native fetch request

import { getBrowserCachedRequest } from "@mihanizm56/fetch-api";

// you can use any library for requests you want
// this is just an exmaple with fetch
const someRequest = async (params) => {
    try {
        // this lib only works with json responses
        const result = await fetch(/* your params */).then(data => data.json());

        return { result };
    } catch (error) {
        // we need to provide an error field in object and give
        // to the cache the ability to understand if it was the good response or not
        return { error: error.message };
    }
}

export const getSomeCachedRequest = (
  someParams,
) => {
  return getBrowserCachedRequest({
    request: () => someRequest(someParams),
    /* your browserCacheParams params */
    strategy: 'StaleWhileRevalidate',
    requestCacheKey: `some request cache key`,
    storageCacheName: `some storage name`,
    expires: 1000 * 60 * 60 * 24 * 365, // 1 year,
    debug: true,
  })
};