import {
BaseEvent,
BaseEventDto,
EventParams,
} from '@hg-ts/events';
import { v7 as uuid } from 'uuid';
import type {
DtoSerializable,
Identifiable,
} from '../types.js';
export const STORED_PROPERTY = Symbol('Domain event stored');
export type DomainEventDto = BaseEventDto & {
id: string;
entityName: string;
entityId: string;
};
export type DomainEventParams
= EventParams & {
id?: string;
entityName: string;
entityId: string;
[STORED_PROPERTY]?: true;
};
export class DomainEvent extends BaseEvent
implements Identifiable, DtoSerializable {
public readonly id: string;
public readonly entityName: string;
public readonly entityId: string;
public [STORED_PROPERTY]: boolean;
public constructor(params: DomainEventParams) {
super(params);
this.id = params.id ?? DomainEvent.generateId();
this.entityName = params.entityName;
this.entityId = params.entityId;
this[STORED_PROPERTY] = params[STORED_PROPERTY] ?? false;
}
public toDto(): DomainEventDto {
return {
id: this.id,
entityId: String(this.entityId),
entityName: this.entityName,
name: this.name,
body: this.body,
occurredOn: this.occurredOn,
traceId: this.traceId,
};
}
public static generateId(): string {
return uuid();
}
}