GithubHelp home page GithubHelp logo

fullcube / loopback-component-fsm Goto Github PK

View Code? Open in Web Editor NEW
8.0 10.0 0.0 285 KB

Loopback Component Finite State Machine

JavaScript 100.00%
loopback lb2 loopback-component state-machine transition fsm mit fullcube

loopback-component-fsm's Introduction

Loopback Finite State Machine

Greenkeeper badge

Circle CI Dependencies Coverage Status

This loopback component provides a finite state machine (powered by https://github.com/vstirbu/fsm-as-promised) for loopback model instances, enabling precise control over when model instance methods may be called.

When a model method that is controlled by the Finite State Machine is called it will set a global lock that will prevent other copies of the same instance from being transitioned whist the existing transition is still underway. The state machine governs which state transitions may take place at any time given the current state of the instance and handles state change persistence on completion of a given transition.

Installation

  1. Install in you loopback project:

npm install --save loopback-component-fsm

  1. Create a component-config.json file in your server folder (if you don't already have one)

  2. Enable the component inside component-config.json.

{
  "loopback-component-fsm": { }
}

Configuration

  1. Define a state machine events in the mixin configuration for you models.
"mixins": {
  "StateMachine": {
    "stateProperty": "status",
    "settings": {
      "allowForce": true
    },
    "events": [
      { "name": "activate", "from": "none", "to": "active", "transitionOptions": { "skipBeforeSave" : true } },
      { "name": "cancel", "from": "active", "to": "canceled" },
      { "name": "reactivate", "from": "canceled", "to": "active" },
      { "name": "expire", "from": [ "active", "canceled" ], "to": "expired" }
    ]
  }
}

Options:

  • stateProperty

    [String] : The name of the model's state property. (default: 'state')

  • settings

    [Object] : Settings used to control state machine operations. Currently the only supported option is allowForce which when set to true makes it possible to carry out an otherwise invalid state change by passing in { force: true } at method call time. This option can also be set per event. (default: {})

  • events

    [Array] : A list of events available to the state machine. Refer to the FSM As Promised documentation for details on how events should be defined. (default: [])

Implementation:

For each event in the State Machine, a series of model notifications will be sent - one for each stage in a transition - in the following order:

callback state in which the notification executes description
fsm:onleave{stateName} from do something when leaving state stateName
fsm:onleave from do something when leaving any state
fsm:on{eventName} from do something when executing the transition
fsm:onenter{stateName} from do something when entering state stateName
fsm:onenter from do something when entering any state
fsm:onentered{stateName} to do something after entering state stateName (transition is complete)
fsm:onentered to do something after entering any state (transition is complete)

You can act on any of these transition stages by observing the notification. For example:

MyModel.observe('fsm:oncancel', ctx => ctx.instance.doSomething().then(() => ctx))

If you intend to perform an asynchronous operation in a given transition stage, your observer should return a promise that resolves to the ctx argument that was passed to it. Otherwise, you should simply return the ctx object.

Return values

The ctx object will be passed through the entire transition call chain and returned to the original caller. If you would like your caller to receive something other than the full ctx object you can set ctx.res which will be returned instead. More information

Usage

Prototype methods will be attached to model instances for each of the named events in your mixin configuration. For example, the above mixin configuration will result in the following methods being added to MyModel.

  • MyModel.prototype.activate
  • MyModel.prototype.cancel
  • MyModel.prototype.reactivate
  • MyModel.prototype.expire

These methods all accept a first argument that is a settings object that is used by the fsm to determine how it functions (eg passing { force: true } (see allowForce above). All arguments will be available from within the various fsm notifications.

MyModel.findOne()
  .then(instance => {
    log.debug(`Current state is: ${instance.state}`) // Current state is: active
    return instance.cancel()
  })
  .then(instance => {
    log.debug(`Current state is: ${instance.state}`) // Current state is: canceled
    return instance.reactivate({ force: true })
  })
  .then(instance => {
    log.debug(`Current state is: ${instance.state}`) // Current state is: active
  })

In this example, a model instance is loaded from the database and a finite state machine is initialized using the current status of the model instance. The instance is then transitioned to the canceled state, then back to the active state.

More Information

Please refer to the FSM As Promised documentation for more detail on the internals of the state machine implementation.

loopback-component-fsm's People

Contributors

beeman avatar greenkeeper[bot] avatar rahulbile avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback-component-fsm's Issues

When instantiatas, current state is not loaded.

Thank you for writing this mixin. While using, I found a problem. I'm using LB version 3.

Problem is, the StateMachine does not load current state. When I print StateMachine's 'current' local variable after I load my model instance(of course by find method), it always undefined. Needless to say, the error message is "Invalid event in the current state". My model's stateProperty name is 'state'.

I temporarily detour this problem by passing "allowForce" option when call the event method. But it's annoying and defenitely looks like unintended behvior. Can you fix this?

Doc doesn't mention the mixin path

Hi,
Thanks for sharing this component, it's nicely designed.
In order to use it with Loopback Model it seems that the docs doesn't mention to add the path in model-config.json.

"mixins": [
      "loopback/common/mixins",
      "loopback/server/mixins",
      "../common/mixins",
      "./mixins",
      "../node_modules/loopback-component-fsm/lib/mixins"
    ]

Thanks.
/Y

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.