Skip to main content

StateBuilder

@rotorsoft/act-root


@rotorsoft/act-root / act/src / StateBuilder

Type Alias: StateBuilder<TState, TName>

StateBuilder<TState, TName> = object

Defined in: libs/act/src/builders/state-builder.ts:33

Builder interface for defining a state with event sourcing.

Provides a fluent API to configure the initial state, event types, and event handlers (reducers) before moving to action configuration.

Seeโ€‹

Type Parametersโ€‹

TStateโ€‹

TState extends Schema

State schema type

TNameโ€‹

TName extends string = string

State name literal type

Propertiesโ€‹

initโ€‹

init: (init) => object

Defined in: libs/act/src/builders/state-builder.ts:56

Defines the initial state for new state instances.

The init function is called when a new stream is created (first event). It can accept initial data or return a default state.

Parametersโ€‹

initโ€‹

() => Readonly<TState>

Function returning the initial state

Returnsโ€‹

A builder with .emits() to declare event types

emitsโ€‹

emits: <TEvents>(events) => ActionBuilder<TState, TEvents, { }, TName> & object

Declares the event types that this state can emit.

Events represent facts that have happened - they should be named in past tense. Each event is defined with a Zod schema for type safety and runtime validation.

Type Parametersโ€‹
TEventsโ€‹

TEvents extends Schemas

Event schemas type

Parametersโ€‹
eventsโ€‹

ZodTypes<TEvents>

Object mapping event names to Zod schemas

Returnsโ€‹

An ActionBuilder (with optional .patch() to override specific reducers)

Exampleโ€‹
.emits({
Incremented: z.object({ amount: z.number() }),
Decremented: z.object({ amount: z.number() }),
Reset: z.object({})
})

Examplesโ€‹

.init(() => ({ count: 0, created: new Date() }))
.init((data) => ({ ...data, createdAt: new Date() }))