Event
Events are at the heart of event sourcing, serving as the primary building blocks upon which the technique is built. In the Codebricks framework, events play a crucial role in capturing and representing state changes within your application.
Understanding Events
In event sourcing, events are records of significant occurrences that are relevant to the business. They capture a moment in time and turn it into a historical record, containing intention and contextual information to represent state changes.
All events should be named in the past tense, reflecting something that has already happened. Events are immutable objects, stored in an append-only manner, representing undeniable facts.
Implementation
An example event class is located at: Task/src/shared/domain/events/TaskAddedEvent.ts
import { Event } from "@codebricks/codebricks-framework";
export interface TaskAddedEventProperties {
id: string;
aggregateId: string;
aggregateVersion: number;
payload: TaskAddedEventPayload;
occurredAt: Date;
}
export interface TaskAddedEventPayload {
title: string;
description: string;
assigneeId: string;
}
export class TaskAddedEvent extends Event<TaskAddedEventPayload> {
static readonly eventName: string = 'TaskAdded';
constructor(properties: TaskAddedEventProperties) {
super({...properties, name: TaskAddedEvent.eventName});
}
}
Key Components
TaskAddedEventProperties
This interface defines the properties of the TaskAddedEvent
.
export interface TaskAddedEventProperties {
id: string;
aggregateId: string;
aggregateVersion: number;
payload: TaskAddedEventPayload;
occurredAt: Date;
}
TaskAddedEventPayload
This interface defines the payload structure for the TaskAddedEvent
.
export interface TaskAddedEventPayload {
title: string;
description: string;
assigneeId: string;
}
TaskAddedEvent
Class
The TaskAddedEvent
class extends the base Event
class provided by the Codebricks framework.
import { Event } from "@codebricks/codebricks-framework";
export class TaskAddedEvent extends Event<TaskAddedEventPayload> {
static readonly eventName: string = 'TaskAdded';
constructor(properties: TaskAddedEventProperties) {
super({...properties, name: TaskAddedEvent.eventName});
}
}
Other Key Components
- Event Name: The static
eventName
property ensures the event is named consistently. - Constructor: Initializes the event with the given properties and sets the event name.
- Immutability: Events are immutable, ensuring they cannot be altered once created.