Last active
May 18, 2017 18:53
-
-
Save malectro/a7c92d046812445c0239a8a326239adf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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