Get unlimited public & private packages + team-based management with npm Teams.Learn more »

fsm-node

1.1.0 • Public • Published

fsm-node  Build Status

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

Install

npm i fsm-node

DownloadsWeekly Downloads

6

Version

1.1.0

License

MIT

Unpacked Size

11.4 kB

Total Files

7

Last publish

Collaborators

  • avatar