Files
gridpilot.gg/packages/analytics/infrastructure/repositories/InMemoryAnalyticsSnapshotRepository.ts
2025-12-10 12:38:55 +01:00

76 lines
2.4 KiB
TypeScript

/**
* Infrastructure: InMemoryAnalyticsSnapshotRepository
*
* In-memory implementation of IAnalyticsSnapshotRepository for development/testing.
*/
import type { IAnalyticsSnapshotRepository } from '../../domain/repositories/IAnalyticsSnapshotRepository';
import { AnalyticsSnapshot, type SnapshotPeriod, type SnapshotEntityType } from '../../domain/entities/AnalyticsSnapshot';
export class InMemoryAnalyticsSnapshotRepository implements IAnalyticsSnapshotRepository {
private snapshots: Map<string, AnalyticsSnapshot> = new Map();
async save(snapshot: AnalyticsSnapshot): Promise<void> {
this.snapshots.set(snapshot.id, snapshot);
}
async findById(id: string): Promise<AnalyticsSnapshot | null> {
return this.snapshots.get(id) ?? null;
}
async findByEntity(entityType: SnapshotEntityType, entityId: string): Promise<AnalyticsSnapshot[]> {
return Array.from(this.snapshots.values()).filter(
s => s.entityType === entityType && s.entityId === entityId
);
}
async findByPeriod(
entityType: SnapshotEntityType,
entityId: string,
period: SnapshotPeriod,
startDate: Date,
endDate: Date
): Promise<AnalyticsSnapshot | null> {
return Array.from(this.snapshots.values()).find(
s => s.entityType === entityType &&
s.entityId === entityId &&
s.period === period &&
s.startDate >= startDate &&
s.endDate <= endDate
) ?? null;
}
async findLatest(
entityType: SnapshotEntityType,
entityId: string,
period: SnapshotPeriod
): Promise<AnalyticsSnapshot | null> {
const matching = Array.from(this.snapshots.values())
.filter(s => s.entityType === entityType && s.entityId === entityId && s.period === period)
.sort((a, b) => b.endDate.getTime() - a.endDate.getTime());
return matching[0] ?? null;
}
async getHistoricalSnapshots(
entityType: SnapshotEntityType,
entityId: string,
period: SnapshotPeriod,
limit: number
): Promise<AnalyticsSnapshot[]> {
return Array.from(this.snapshots.values())
.filter(s => s.entityType === entityType && s.entityId === entityId && s.period === period)
.sort((a, b) => b.endDate.getTime() - a.endDate.getTime())
.slice(0, limit);
}
// Helper for testing
clear(): void {
this.snapshots.clear();
}
// Helper for seeding demo data
seed(snapshots: AnalyticsSnapshot[]): void {
snapshots.forEach(s => this.snapshots.set(s.id, s));
}
}