2.0.0 • Published 5 years ago

cache-hit v2.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

cache-hit

JavaScript promise caching library

Types

options

OptionRequiredDescriptionDefault value
timeToLiveNoAn integer value that the cache is valid for in millisecondsNumber.POSITIVE_INFINITY

Omitting timeToLive Option

This will result in an infinite cache. Once a successful response is received, the promise will never be invoked a second time.

Cache

interface Cache {
  read: () => Promise
}

API

createCache(promiseReturningFunction: () => Promise, options): Cache

PARAMETERS

promiseReturningFunction

A function that when called, will return a promise. The promiseReturningFunction is invoked from within the library.

options

Object of options. Supported options are listed in the Types section.

Return Value

Returns a Cache type.

Cache.read({ key: string, forceRead: Boolean }, ...promiseParameters: any): Promise

PARAMETERS

key

Data returned will be stored in the cache based on a key. Whenever reads occur, the cache will first be checked for a valid cache value and return the cached value or in the case of an invalid cache, the promise will be invoked and data will be stored in the cache depending on your timeToLive option.

forceRead

Defaulted to false. If this is set to true, the promise will be invoked regardless of the caching policy.

promiseParameters

Parameters that will be spread into the promiseReturningFunction. An example of calling this function exists below.

getAccountsApiCached.read({ key: 'some-key' }, param1, param2);

Example

// get-accounts.js
import createCache from 'cache-hit';

const getAccountsApi = (username, sessionId) => fetch(`/accounts/${username}`, { headers: { sessionId });

const getAccountsApiCached = createCache(getAccountsApi, { timeToLive: 15000 }); // timeToLive in milliseconds

export default getAccountsApiCached;
// accounts.js
import getAccountsApiCached from './get-accounts';

const getAccounts = (username, sessionId) => {
  const key = username; // unique key for this cache instance
  return getAccountsApi
          .read({ key: key, forceInvoke: false }, username, sessionId)
          .then((response) => dispatch(someAction(response)))
          .catch((error) => dispatch(someErrorAction(error)));
};

Errors

All errors will need to be handled after calling the read method. The cache will not be updated on any rejected promises.

2.0.0

5 years ago

1.0.0

5 years ago

0.5.0

5 years ago

0.4.1

5 years ago

0.4.0

5 years ago

0.3.5

5 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago