@rohan89/mongoose-state-machine
v0.5.2
Published
A Mongoose plugin that implements a state machine into a schema
Downloads
46
Readme
@rohan89/mongoose-state-machine
A Mongoose plugin that implement a state machine into a Mongoose schema.
The plugin is based on javascript-state-machine.
Install
npm install @rohan89/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, defaultstatus
)
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 '@rohan89/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!)
Test
- Copy the
.env.example
file to.env.test.local
and fill in the values - Fill in the values in the
.env.test.local
file, for example:- DB_MONGO_URI=mongodb://localhost:27017/test
- Run
docker compose up
to start the MongoDB container for the test environment - So, run
npm test
to run the tests