Skip to content

Instantly share code, notes, and snippets.

@blasut
Last active May 12, 2020 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blasut/5ca4464ab64d056ed8fd0b66c6ca52da to your computer and use it in GitHub Desktop.
Save blasut/5ca4464ab64d056ed8fd0b66c6ca52da to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchCreditCheck = (context, event) => new Promise((resolve, reject) => {
console.log("fetch credit check")
return resolve({
status: "APPROVED"
})
});
const fetchBankIdStatus = (context, event) => new Promise((resolve, reject) => {
console.log("fetch bankid status")
return resolve({
auth_status: "AWAITING_SIGNATURE"
})
});
const isApproved = (context, event, meta) => {
return event?.data?.status == "APPROVED";
};
const isComplement = (context, event) => {
return event?.data?.status == "AWAITING_APPROVAL";
};
const isRejected = (context, event) => {
return event?.data?.status == "REJECTED";
};
const CheckoutMachine = Machine({
id: 'checkout',
initial: 'OpenBankID',
context: {
creditCheck: null
},
states: {
OpenBankID: { on: { SUCCESS: 'BankIDStatus', FAILURE: 'BankIDFailed' } },
BankIDFailed: { on: { RETRY: 'OpenBankID' } },
BankIDStatus: {
initial: 'polling',
// https://github.com/davidkpiano/xstate/issues/567
states: {
polling: {
invoke: {
id: 'pollBankId',
src: (context, event) => (callback, onReceive) => {
// This will send the 'INC' event to the parent every second
const id = setInterval(() => {
// fetch bankid status here?
return callback('INC')
}, 1000);
//TODO set the context to the bankid status
// Perform cleanup
return () => clearInterval(id);
},
},
},
},
on: {
INC: 'CreditCheck'
},
},
// Perhaps make this into a child FSM?
CreditCheck: {
initial: 'checking',
states: {
checking: {
invoke: {
id: 'checking',
src: fetchCreditCheck,
onDone: [ {
target: '#OrderComplete',
cond: isApproved,
actions: assign({
creditCheck: (_, event) => event.data
})
},
{
target: 'complement',
cond: isComplement,
actions: assign({
creditCheck: (_, event) => event.data
})
},
{
target: 'rejected',
cond: isRejected,
actions: assign({
creditCheck: (_, event) => event.data
})
},
],
onError: 'rejected'
},
on: {
CANCEL: 'rejected'
}
},
complement: {},
rejected: {},
}
},
OrderComplete: {
id: "OrderComplete",
},
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment