fsm-node
v1.1.0
Published
A simple finite state machine with a straighforward API.
Downloads
15
Readme
fsm-node
A minimalist Node.js finite state machine.
Install
$ npm install fsm-node
Usage
fsm-node
has a simple API that expects a set of states and a set of events that define how the event machine moves through the different states. Invalid configuration objects passed into fsm
will raise an error with helpful usage information.
const { fsm } = require('fsm-node');
const machine = fsm({
initial: 'draft', // optional, defaults to first item in states array
states: [
'draft',
'pending',
'published',
'deleted',
],
events: [{
name: 'submit',
from: 'draft',
to: 'pending',
}, {
name: 'revert',
from: ['pending', 'published'], // "from" allows strings and an array of strings
to: 'draft',
}, {
name: 'delete',
from: '*', // all states except "to" state ('deleted')
to: 'deleted',
}, {
name: 'accept',
from: 'pending',
to: 'published',
}, {
name: 'reject',
from: 'pending',
to: 'draft',
}]
});
machine.on('event', (previousState, action, newState) => {
console.log(`EVENT: previousState: ${previousState}, action: ${action}, newState: ${newState}`);
});
machine.on('ignored', (state, action) => {
console.log(`IGNORED: state: ${state}, action: ${action}`);
});
console.log(machine.state);
console.log(machine.done);
machine.event('submit');
console.log(machine.state);
machine.event('delete');
console.log(machine.done);
machine.event('submit');
This produces:
draft
false
EVENT: previousState: draft, action: submit, newState: pending
pending
EVENT: previousState: pending, action: delete, newState: deleted
true
IGNORED: state: deleted, action: submit