Skip to content

Instantly share code, notes, and snippets.

@zsimo
Created June 29, 2020 12:28
Show Gist options
  • Save zsimo/c948100b9b4a60d28e7989356a453757 to your computer and use it in GitHub Desktop.
Save zsimo/c948100b9b4a60d28e7989356a453757 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
function isOk (context) {
return context.errors_counter < context.THRESHOLD;
}
function isOKAndShouldSendSolvedEmail (context, event) {
return !event.error && context.should_send_solved_email === true;
}
var machine = Machine({
id: 'error_manager',
initial: 'ready',
context: {
errors_counter: 0,
should_send_solved_email: false,
THRESHOLD: 3
},
states: {
ready: {
on: {
UPDATE: [{
target: "should_send_error_email",
actions: ['update_counter'],
cond: "error_and_should_not_send_solved_email"
}, {
target: "send_solved_email",
actions: ['update_counter'],
cond: "not_error_and_should_send_solved_email"
}]
}
},
should_send_error_email: {
on: {
'': [
{ target: 'ready', cond: "not_send" },
{ target: 'send_error_email', cond: "send" },
]
}
},
send_solved_email: {
on: {
"": {
"target": "ready",
"actions": ["send_solved_email"]
}
},
exit: ["deactivate_solved_email"]
},
send_error_email: {
on: {
"": {
"target": "await",
"actions": ["send_error_email"]
}
},
exit: ["activate_solved_email"],
},
"await": {
after: {
AWAIT_DELAY: 'ready'
},
on: {
UPDATE: {
target: "send_solved_email",
cond: "not_error_and_should_send_solved_email"
}
},
exit: ["reset_counter"]
}
}
},
{
actions: {
update_counter: assign({
errors_counter: function (context, event) {
if (event.error) {
return context.errors_counter + 1;
}
return 0;
}
}),
reset_counter: assign({
errors_counter: 0
}),
activate_solved_email: assign({
should_send_solved_email: true
}),
deactivate_solved_email: assign({
should_send_solved_email: false
}),
send_solved_email: function (context, event) {
console.log("send_solved_email");
},
send_error_email: function (context, event) {
console.log("send_error_email");
}
},
guards: {
not_send: isOk,
send: function (context) {
return !isOk(context);
},
not_error_and_should_send_solved_email: isOKAndShouldSendSolvedEmail,
error_and_should_not_send_solved_email: function (context, event) {
return !isOKAndShouldSendSolvedEmail(context, event);
}
},
delays: {
AWAIT_DELAY: 2000
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment