0.6.3 • Published 3 years ago

typeorm-state-machine v0.6.3

Weekly downloads
44
License
ISC
Repository
github
Last release
3 years ago

Typeorm State Machine

Declarative state machine definition for typeorm entity classes Based on javascript-state-machine implementation

Why?

Usage

Imagine you have some payment model. This payment has statuses:

  • new
  • registered
  • held
  • charged
  • error
  • refunded
enum Status {
    NEW = 'new',
    REGISTERED = 'registered',
    HELD = 'held',
    CHARGED = 'charged',
    ERROR = 'error',
    REFUNDED = 'refunded',
}

@StateMachine({
    transitions: [
        { name: 'register', from: Status.NEW, to: Status.REGISTERED },
        { name: 'hold', from: Status.REGISTERED, to: Status.HELD },
        { name: 'charge', from: Status.HELD, to: Status.CHARGED },
        { name: 'fail', from: [Status.NEW, Status.HELD, STATUS.REGISTERED], to: Status.ERROR },
        { name: 'refund', from: Status.CHARGED, to: Status.REFUNDED },
    ]
})
@Entity()
class Payment {
    @Column()
    guid: string;

    @Column()
    externalId: string;

    @Column()
    amount: number;

    @Column()
    status: Status;
}

Also you need interface with these methods and same name as entity

interface Payment {
    register(): void;
    hold(): void;
    charge(): void;
    fail(): void;
    refund(): void;
}

After the entity will be loaded - state machine initialized with proper status. And you can use methods from interface which was implemented while entity loading

payment.register();
payment.hold();
payment.charge();
payment.refund();

payment.register() // will fail, becauze it is incorrect state transition

Options

  • saveAfterTransition - all transitions become promisified and you can use it like await payment.hold(). Entity is also will be saved in database (Default false)
  • autoImplementAll - all methods provided in state machine definition are auto implemented while loading. (Default true)

Samples

See samples directory. Also this samples are used in tests, so you can be sure that it is just working

0.6.3

3 years ago

0.6.2

3 years ago

0.6.1

3 years ago

0.6.0

3 years ago

0.5.0

3 years ago

0.4.0

3 years ago

0.3.5

4 years ago

0.3.4

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.1

4 years ago

0.2.2

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago