Last active
October 7, 2016 10:25
-
-
Save esamattis/14bbe3c803092fa234efade31de6e134 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
import deepFreeze from "deep-freeze"; | |
import isPlainObject from "lodash/fp/isPlainObject"; | |
export function wrapSanityChecks(reducer) { | |
if (process.env.NODE_ENV === "production") return reducer; | |
return (state, action) => { | |
if (!isPlainObject(action)) { | |
const msg = `Bad action object of type ${typeof action}`; | |
console.log(msg, action); | |
throw new Error(msg); | |
} | |
// Actions should be serializable so that they can be replayed using | |
// Redux Devtools. Serializable actions also would allow sending them | |
// over network etc. | |
try { | |
JSON.stringify(action); | |
} catch (error) { | |
const msg = "Invalid action! Actions must be serializable"; | |
console.log(msg, action); | |
throw new Error(msg); | |
} | |
// Ensure immutable state and actions. Reducers should never mutate | |
// those. | |
state = reducer(deepFreeze(state), deepFreeze(action)); | |
if (!isPlainObject(state)) { | |
const msg = `State screwed by action ${action.type}. Store state is now '${typeof state}'`; | |
console.log(msg, action); | |
throw new Error(msg); | |
} | |
return state; | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment