Skip to content

Instantly share code, notes, and snippets.

@njdancer
Last active October 9, 2019 05:44
Show Gist options
  • Save njdancer/9c0e30453be3711ef6f4ebbb637a4a6c to your computer and use it in GitHub Desktop.
Save njdancer/9c0e30453be3711ef6f4ebbb637a4a6c to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const requestMachine = Machine(
{
context: {
failGracefully: false,
tokenUpdated: false,
},
id: "request",
initial: "loading",
on: {
REFRESH: ".loading",
TOKEN: {
actions: "assignToken",
target: ".prev",
},
},
states: {
failed: {
after: {
TTL: "loading",
},
entry: "notifyParentFailed",
initial: "check",
states: {
auth: {
on: {
"": {
cond: "shouldAutoRefresh",
target: "#request.loading",
},
TOKEN: {
actions: "assignToken",
target: "#request.loading",
},
},
},
check: {
on: {
"": [
{
cond: "shouldFailGracefully",
target: "#request.loaded",
},
{
cond: "isAuthError",
target: "auth",
},
{
target: "other",
},
],
},
},
other: {
on: {
"": {
cond: "shouldFinalize",
target: "#request.error"
}
}
},
},
},
loaded: {
on: {
"": {
cond: "shouldFinalize",
target: "done"
}
},
after: {
TTL: "loading",
},
},
loading: {
entry: "resetTokenUpdated",
invoke: {
id: "initialRequest",
onDone: {
actions: ["assignData", "resetTokenUpdated"],
target: "loaded",
},
onError: {
actions: "assignError",
target: "failed",
},
src: "performRequest",
},
on: {
REFRESH: {},
TOKEN: {
actions: ["assignToken", "setTokenUpdated"],
},
},
},
prev: {
target: "loading",
type: "history",
},
done: {
type: "final"
},
error: {
type: "final"
}
},
},
{
actions: {
assignData: assign({ data: (context, event) => event.data }),
assignError: assign({ error: (context, event) => event.data }),
assignToken: assign({
token: (context, event) => event.token,
}),
notifyParentFailed: (context, event) =>
sendParent({ error: context.error, type: "FAILED" }),
notifyParentLoaded: (context, event) =>
sendParent({ data: context.data, type: "LOADED" }),
resetError: assign({ error: (context, event) => null }),
resetTokenUpdated: assign({ tokenUpdated: false }),
setTokenUpdated: assign({ tokenUpdated: true }),
},
delays: {
TTL: (context, event) => (context.ttl != null ? context.ttl : 2147483647),
},
guards: {
shouldFinalize: (context, event) => context.ttl == null,
isAuthError: (context, event) => false,
shouldAutoRefresh: (context, event) => context.tokenUpdated,
shouldFailGracefully: (context, event) =>
context != null && context.failGracefully && context.data != null,
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment