Skip to main content
Version: Next

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, CacheFirststrategy for the request
requestCacheKeystringmain request cache key
storageCacheNamestringmain request storage key
expiresnumbertime in ms for the request cache to be expired
expiresToDatenumbertime in ms for the request cache to be expired to the selected date only
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
minAllowedQuotanumbermin request cache allowed quota in cache-storage