Skip to content

Instantly share code, notes, and snippets.

@mweststrate
Last active September 25, 2017 15:07
Show Gist options
  • Save mweststrate/ab978703e57db925483b7840c09c76be to your computer and use it in GitHub Desktop.
Save mweststrate/ab978703e57db925483b7840c09c76be to your computer and use it in GitHub Desktop.
Patch based middleware for atomic actions
import { recordPatches } from "mobx-state-tree"
const runningActions = new Map()
export function atomicAsyncPatch(call, next) {
switch (call.type) {
case "action":
return atomic(call, next)
case "process_spawn": {
const recorder = recordPatches(call.tree)
runningActions.set(call.id, recorder)
break
}
case "process_resume":
case "process_resume_error": {
const recorder = runningActions.get(call.id)
recorder.resume()
try {
return next(call)
} finally {
recorder.stop()
}
}
case "process_throw":
runningActions.get(call.id).undo()
runningActions.delete(call.id)
break
case "process_return":
runningActions.delete(call.id)
break
}
return next(call)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment