Skip to main content
zerotal

Documentation


Documentation / @zerotal/orm / index / State

Function: State()

State<TBase>(Base): {(...args): State; stateField: string; states?: Record<string, StateDefinition<string, any>>; onTransition: void; prototype: State<any>; } & TBase

Defined in: packages/orm/src/model/State.ts:144

Mixin that adds finite-state-machine behaviour to a model. Compose it so only models that declare a workflow carry the API — transitionTo / forceState / onTransition and the states + stateField statics never appear on models that don't use them.

Declare the machine in static states (use as const for exact state typing) and, optionally, override static stateField when the state column isn't status. Each transition validates that the move is allowed, runs the target state's guard, persists via save(), then fires onTransition callbacks.

Type Parameters

TBase

TBase extends Constructor

Parameters

Base

TBase

Returns

Example

const States = {
  pending:   { canTransitionTo: ["active", "cancelled"] as const },
  active:    { canTransitionTo: ["expired"] as const,
               guard: (s: Subscription) => { if (!s.stripeId) throw new StateError(...); } },
  expired:   { canTransitionTo: [] as const },
  cancelled: { canTransitionTo: [] as const },
} as const;

class Subscription extends BaseModelWith(State) {
  static states = States;
  @column() status!: keyof typeof States;
}

const [ok, err] = await sub.transitionTo("active");
if (!ok) return json({ error: err.message }, 422);