diff --git a/src/entities/ParkingRepositoryEntities.ts b/src/entities/ParkingRepositoryEntities.ts index 076669d..36ca488 100644 --- a/src/entities/ParkingRepositoryEntities.ts +++ b/src/entities/ParkingRepositoryEntities.ts @@ -8,7 +8,7 @@ export interface IParkingStructure extends IEntityWithTimestamp, IEntityWithId { name: string; } -export interface IParkingStructureTimestampRecord extends IEntityWithTimestamp { +export interface IParkingStructureTimestampRecord { timestampMs: number; id: string; spotsAvailable: number; diff --git a/src/repositories/InMemoryParkingRepository.ts b/src/repositories/InMemoryParkingRepository.ts index ae6bdef..db0e543 100644 --- a/src/repositories/InMemoryParkingRepository.ts +++ b/src/repositories/InMemoryParkingRepository.ts @@ -20,8 +20,33 @@ export class InMemoryParkingRepository implements ParkingGetterSetterRepository addOrUpdateParkingStructure = async (structure: IParkingStructure): Promise => { this.structures.set(structure.id, { ...structure }); + await this.addHistoricalDataForStructure(structure); }; + private addHistoricalDataForStructure = async (structure: IParkingStructure): Promise => { + const now = Date.now(); + const lastAdded = this.dataLastAdded.get(structure.id); + + function parkingLoggingIntervalExceeded() { + return !lastAdded || (now - lastAdded.getTime()) >= PARKING_LOGGING_INTERVAL_MS; + } + + if (parkingLoggingIntervalExceeded()) { + const timestampRecord: IParkingStructureTimestampRecord = { + id: structure.id, + spotsAvailable: structure.spotsAvailable, + timestampMs: now, + }; + + if (!this.historicalData.has(structure.id)) { + this.historicalData.set(structure.id, []); + } + + this.historicalData.get(structure.id)?.push(timestampRecord); + this.dataLastAdded.set(structure.id, new Date(now)); + } + } + clearParkingStructureData = async (): Promise => { this.structures.clear(); }; diff --git a/test/repositories/InMemoryParkingRepositoryTests.test.ts b/test/repositories/InMemoryParkingRepositoryTests.test.ts index 41ea843..b3de36d 100644 --- a/test/repositories/InMemoryParkingRepositoryTests.test.ts +++ b/test/repositories/InMemoryParkingRepositoryTests.test.ts @@ -57,8 +57,8 @@ describe("InMemoryParkingRepository", () => { jest.setSystemTime(now + PARKING_LOGGING_INTERVAL_MS + 60); await repository.addOrUpdateParkingStructure(testStructure); - expect(historicalData.get(testStructure.id)).toContain(expectedTimestampRecordMatcher); - expect(historicalData.get(testStructure.id)).toContain({ + expect(historicalData.get(testStructure.id)).toContainEqual(expectedTimestampRecordMatcher); + expect(historicalData.get(testStructure.id)).toContainEqual({ ...expectedTimestampRecordMatcher, timestampMs: now + PARKING_LOGGING_INTERVAL_MS + 60, });