Created
August 17, 2021 21:44
-
-
Save Greg-Hitchon/38ba68bd14170bd77b8f74fd4270ad61 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { entity } from 'durable-functions'; | |
import { State, interpret } from 'xstate'; | |
import { getMachine } from './machines'; | |
import { updateEntity, waitForMachineToResolve } from '../Shared/utilities'; | |
export default entity(async (context) => { | |
let machine = getMachine(context); | |
switch (context.df.operationName) { | |
case 'send': | |
try { | |
// Initilize | |
const input = context.df.getInput() as any; | |
// Get previous state | |
const previousState = context.df.getState( | |
() => machine.initialState | |
) as typeof machine.initialState; | |
// Set up machine | |
const state = machine.resolveState(State.create(previousState)); | |
const service = interpret(machine); | |
service.start(state); | |
// Send action | |
if (service.state.nextEvents.some(x => x == 'INITIALIZE')) { | |
service.send({ type: "INITIALIZE", id: context.df.entityId.key, config: machine.config }) | |
} | |
else { | |
// Kickoff some action | |
service.send(input.data) | |
} | |
// Wait for state to settle | |
await waitForMachineToResolve(service); | |
// Update local entity | |
context.df.setState(service.state); | |
let events = service.state.nextEvents.filter(x => x.toLowerCase().startsWith("process_") && service.nextState({ type: x, isInternalXState: true })?.changed); | |
// Update remote entity | |
if (service.state.context.metadata.domainEntityId) { | |
await updateEntity(service.state.context.metadata.domainEntityId, JSON.stringify(service.state), JSON.stringify(machine.config), JSON.stringify(events)) | |
} | |
service.stop(); | |
} | |
catch (error) { | |
context.log(error); | |
} | |
break; | |
default: | |
break; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment