Skip to main content

f ( model )

Accelerate development of compositional, safe and ergonomic applications

Functional and Algebraic Domain Modeling

TypeScript

StateStored systems

State-stored systems are traditional systems that are only storing the current state by overwriting the previous state in the storage.

EventSourced + StateStored

Both types of systems can be designed by using only these three functions (decide, evolve, react) and three generic parameters (command, event, state).


export const orderDecider: Decider<OrderCommand, Order | null, OrderEvent> =
new Decider<OrderCommand, Order | null, OrderEvent>(
(command, currentState) => {
switch (command.kind) {
case "CreateOrderCommand":
return (currentState === null)
? [
{
version: 1,
decider: "Order",
kind: "OrderCreatedEvent",
id: command.id,
restaurantId: command.restaurantId,
menuItems: command.menuItems,
final: false,
},
]
: [
{
version: 1,
decider: "Order",
kind: "OrderNotCreatedEvent",
id: command.id,
restaurantId: command.restaurantId,
menuItems: command.menuItems,
final: false,
reason: "Order already exist!",
},
];
case "MarkOrderAsPreparedCommand":
return (currentState !== null && currentState.orderId === command.id)
? [
{
version: 1,
decider: "Order",
kind: "OrderPreparedEvent",
id: currentState.orderId,
final: false,
},
]
: [
{
version: 1,
decider: "Order",
kind: "OrderNotPreparedEvent",
id: command.id,
reason: "Order does not exist!",
final: false,
},
];
default: {
// Exhaustive matching of the command type
const _: never = command;
return [];
}
}
},
(currentState, event) => {
switch (event.kind) {
case "OrderCreatedEvent":
return {
orderId: event.id,
restaurantId: event.restaurantId,
menuItems: event.menuItems,
status: "CREATED",
};
case "OrderNotCreatedEvent":
return currentState;
case "OrderPreparedEvent":
return currentState !== null
? {
orderId: currentState.orderId,
restaurantId: currentState.restaurantId,
menuItems: currentState.menuItems,
status: "PREPARED",
}
: currentState;
case "OrderNotPreparedEvent":
return currentState;
default: {
// Exhaustive matching of the event type
const _: never = event;
return currentState;
}
}
},
null,
);