Last active
January 7, 2020 15:50
-
-
Save medelman17/9447f993b2ea789818f38c45a8b8f365 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
const photon = { | |
characters: { | |
create({data}) { | |
return new Promise((resolve, reject) => { | |
setTimeout(reject, 10) | |
}) | |
} | |
} | |
} | |
const machine = createPhotonMachine({ | |
data: {}, | |
retries: 0 | |
}) | |
function createPhotonMachine(context) { | |
const config = getPhotonMachineConfig(context, uuid()); | |
const options = getPhotonMachineOptions(context); | |
return Machine(config, options); | |
} | |
function getPhotonMachineConfig(context, id) { | |
return { | |
id, | |
initial: "demo", | |
context, | |
states: { | |
demo: { | |
on: { | |
START_MACHINE: "idle" | |
} | |
}, | |
idle: { | |
entry: send("TRY", { delay: "backoff" }), | |
on: { | |
TRY: { target: "pending" } | |
} | |
}, | |
pending: { | |
invoke: { | |
id: "photon", | |
src: "photon", | |
onDone: { | |
target: "done", | |
actions: ["resolve"] | |
}, | |
onError: { | |
target: "failure" | |
} | |
} | |
}, | |
failure: { | |
on: { | |
"RETRY": [ | |
{ target: "idle", cond: "canRetry", actions: "increment" }, | |
{ target: "done" } | |
] | |
} | |
}, | |
done: { | |
type: "final", | |
data: (_, context) => context | |
} | |
} | |
}; | |
} | |
function getPhotonMachineOptions(context) { | |
return { | |
guards: { | |
canRetry: ({ retries }) => retries < 2 | |
}, | |
actions: { | |
resolve: assign({ | |
result: (_, event) => event.result | |
}), | |
increment: assign({ | |
retries: ({ retries }) => retries + 1 | |
}) | |
}, | |
activities: {}, | |
services: { | |
photon: ({ data }, _) => photon.characters.create({ data }) | |
}, | |
delays: { | |
backoff: ({ retries }) => retries * 500 | |
} | |
}; | |
} | |
function uuid() { | |
return "photon" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment