Created
December 21, 2016 08:35
-
-
Save simmo/06e6a1a5bf3e2c018ba3ccbaf98c5bf0 to your computer and use it in GitHub Desktop.
Redux Middleware: Cacheable Promises
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
// Utility to check if value is a Promise | |
function isPromise(value) { | |
if (value !== null && typeof value === 'object') { | |
return value && typeof value.then === 'function' | |
} | |
return false | |
} | |
// Cache | |
let cache = {} | |
export default function promiseMiddleware({ dispatch }) { | |
return (next) => (action) => { | |
// If it's not a promise, skip | |
if (!isPromise(action.payload)) { | |
return next(action) | |
} | |
// Check the cache | |
if (cache.hasOwnProperty(action.type)) { | |
// In the cache, return Promise in progress | |
return cache[action.type] | |
} else { | |
// Not in cache, trigger pending action | |
next({ | |
type: `${action.type}_PENDING` | |
}) | |
// Handle Promise resolution | |
const handleResolution = (error = false, payload = null) => { | |
// Remove from cache | |
delete cache[action.type] | |
return dispatch({ | |
type: `${action.type}_${error ? 'REJECTED' : 'FULFILLED'}`, | |
payload, | |
error | |
}) | |
} | |
// Add Promise to cache and return it | |
return cache[action.type] = action.payload.then(handleResolution.bind(null, false), handleResolution.bind(null, true)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment