Skip to content

Instantly share code, notes, and snippets.

@malectro
Last active May 18, 2017 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malectro/a7c92d046812445c0239a8a326239adf to your computer and use it in GitHub Desktop.
Save malectro/a7c92d046812445c0239a8a326239adf to your computer and use it in GitHub Desktop.
export const cached = ({ttl = 60000}) => wrappedFunc => {
// require the action creator to have a KEY
if (!wrappedFunc.KEY) {
throw new Error('Must use key() decorator first before fetching');
}
// the higher order action creator
const cachedWrapped = (...args) => (dispatch, getState) => {
const keyValue = wrappedFunc.KEY.apply(this, args);
// check if the action is cached
const cacheItem = getState().cache[keyValue];
if (cacheItem && cacheItem.expireTime > Date.now()) {
return;
}
// assume the wrapped action creator returns an api promise
const requestPromise = wrappedFunc(...args)(dispatch, getState).then(response => {
// set the action as cached
dispatch(setCache(keyValue));
});
return requestPromise;
};
// redecorate the new action creator with the original key
return key(wrappedFunc.KEY)(cachedWrapped);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment