0.4.2 • Published 4 years ago

@safer-bwd/mongoose-state-machine v0.4.2

Weekly downloads
19
License
ISC
Repository
github
Last release
4 years ago

@safer-bwd/mongoose-state-machine

Build Status

A Mongoose plugin that implement a state machine into a Mongoose schema.

The plugin is based on javascript-state-machine.

Install

npm install @safer-bwd/mongoose-state-machine --save

Options

  • stateMachine Object The state machine declaration object (javascript-state-machine)
  • fieldName string The name of the schema field that stores the current state (optional, default status)

Usage

First you need to declare a schema and extend it using the plugin.

Important: The following schema paths cannot be used: state, is, can, cannot, transitions, allTransitions, allStates and transitions names. Because they conflict with javascript-state-machine

import mongoose from 'mongoose';
import stateMachinePlugin from '@safer-bwd/mongoose-state-machine';

// schema declaration
const matterSchema = new mongoose.Schema({ 
  matterState: String // field for storing state 
});

// state machine declaration
const stateMachine = {
  init: 'solid',
  transitions: [
    { name: 'melt', from: 'solid', to: 'liquid' },
    { name: 'freeze', from: 'liquid', to: 'solid' },
    { name: 'vaporize', from: 'liquid', to: 'gas' },
    { name: 'condense', from: 'gas', to: 'liquid' }
  ],
  methods: {
    onMelt() { console.log('I melted') },
    onFreeze() { console.log('I froze') },
    onVaporize() { console.log('I vaporized') },
    onCondense() { console.log('I condensed') }
  }
};

// extend schema with the plugin
matterSchema.plugin(stateMachinePlugin, { 
  fieldName: 'matterState', 
  stateMachine 
});
  
const Matter = mongoose.model('Matter', schema);

Now you can use javascript-state-machine API after created or retrieved a document from a database.

Important: The plugin does not manipulate data in a database. To save state in the database you need to use Mongoose API.

// create document
const matter = new Matter();
matter.matterState;   // solid (init state);
matter.is('solid');   // true
matter.is('liquid');  // false
matter.can('melt');   // true
matter.can('freeze'); // false

// transition
matter.melt();        // I melted!
matter.matterState;   // liquid 
await matter.save();  // save state

// retrieving from a database
const found = Matter.findById(matter.id);
found.matterState;  // liquid;
found.vaporize();   // I vaporized!
found.matterState;  // gas
found.melt();       // throw error

matter.matterState = 'solid'; // gas (no effect!)
0.4.2

4 years ago

0.4.1

4 years ago

0.4.0

4 years ago

0.3.1

4 years ago

0.3.0

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago