Skip to content

Instantly share code, notes, and snippets.

@vin-e
Created July 17, 2020 03:51
Show Gist options
  • Save vin-e/7645667212510c6135b1566219a3c714 to your computer and use it in GitHub Desktop.
Save vin-e/7645667212510c6135b1566219a3c714 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const schemaMachineConfig = {
initial: 'idle',
context: {
schemaToLoad: undefined,
schemas: {}
},
states: {
idle: {
on: {
LOAD: [{
target: 'loaded',
cond: 'hasEventSchemaNameDefined'
}, {
target: 'loading',
actions: 'setSchemaToLoad',
cond: 'hasEventSchemaName'
}, {
target: 'failed'
}]
}
},
loading: {
invoke:{
src: 'loadSchema',
onDone: {
target: 'loaded',
actions: 'setSchema'
},
onError: 'failed'
}
},
loaded: {
on: {
'': {
target: 'idle',
actions: [
'sendToParent',
'resetSchemaToLoad'
]
}
}
},
failed: {
after: {
500: 'idle'
}
}
}
}
const SchemaMachine = Machine(schemaMachineConfig, {
guards: {
hasEventSchemaName: (_, event) => !!(event).schemaName,
hasEventSchemaNameDefined: (context, event) => {
const schemaName = (event).schemaName
return !!schemaName && !!context.schemas[schemaName]
}
},
actions: {
resetSchemaToLoad: assign((_) => ({
schemaToLoad: undefined
})),
sendToParent: (context) => sendParent('LOADED_SCHEMA', context.schemas[context.schemaToLoad]),
setSchema: assign({
schemas: (context, event) => ({
...context.schemas,
[context.schemaToLoad]: {
...(event).data
}
})
}),
setSchemaToLoad: assign({
schemaToLoad: (_, event) => (event).schemaName
})
},
services: {
loadSchema: (_context) => new Promise((resolve, reject) => {
resolve({
type: 'object',
properties: {
testId: { type: 'number' },
name: { type: 'string' },
test_type: {
type: 'string',
default: 'something'
}
},
required: ['name', 'test_type']
})
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment