Last active
September 21, 2017 21:50
-
-
Save dounan/207cc05e47a97e22494739fcb42e2c3c to your computer and use it in GitHub Desktop.
Example of how Flexport uses mutation-sentinel
This file contains 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 {configureSentinel} from "mutation-sentinel"; | |
... | |
// Called on initial app load, and when route changes. | |
function updateConfig(route) { | |
if (/* mutation-sentinel enabled for route */) { | |
configureSentinel({shouldIgnore, mutationHandler}); | |
} else { | |
configureSentinel({shouldIgnore, mutationHandler: () => {}}); | |
} | |
} | |
// Some libraries will mutate their objects internally. | |
function shouldIgnore(val) { | |
return ( | |
moment.isMoment(val) || | |
React.isValidElement(val) || | |
// Appending a File wrapped with a sentinel to FormData does not work | |
(typeof File !== "undefined" && val instanceof File) | |
); | |
} | |
function mutationHandler(mutation) { | |
// We don't care about reporting the same exact mutation multiple times. | |
if (hasSeenSentinelMutation()) { | |
return; | |
} | |
console.warn("Mutation detected by sentinel!", mutation); | |
/* Also log to Sentry (our production error tracker) */ | |
} | |
const seenMutations = new Set(); | |
function hasSeenSentinelMutation() { | |
// Since the sentinel catches the mutation at the exact place in the code | |
// where the mutation is executed, we can use the stack trace to uniquely | |
// identify a mutation. | |
const e = new Error(); | |
const stack = e.hasOwnProperty("stack") ? e.stack : null; | |
if (stack != null) { | |
const mutationHash = murmur.murmur3(stack, 0); | |
if (seenMutations.has(mutationHash)) { | |
return true; | |
} | |
seenMutations.add(mutationHash); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment