73 lines
2.4 KiB
TypeScript
73 lines
2.4 KiB
TypeScript
import { Repository, LessThan } from 'typeorm';
|
|
import { AppDataSource } from '../ormconfig';
|
|
import { IGameSnapshotRepository } from '../../Domain/IRepository/IGameSnapshotRepository';
|
|
import { GameSnapshotAggregate, SnapshotTrigger } from '../../Domain/Game/GameSnapshotAggregate';
|
|
|
|
export class GameSnapshotRepository implements IGameSnapshotRepository {
|
|
private repository: Repository<GameSnapshotAggregate>;
|
|
|
|
constructor() {
|
|
this.repository = AppDataSource.getRepository(GameSnapshotAggregate);
|
|
}
|
|
|
|
async save(snapshot: GameSnapshotAggregate): Promise<GameSnapshotAggregate> {
|
|
return await this.repository.save(snapshot);
|
|
}
|
|
|
|
async findLatestByGameId(gameId: string): Promise<GameSnapshotAggregate | null> {
|
|
return await this.repository.findOne({
|
|
where: { gameid: gameId },
|
|
order: { createdat: 'DESC' }
|
|
});
|
|
}
|
|
|
|
async findByGameId(gameId: string): Promise<GameSnapshotAggregate[]> {
|
|
return await this.repository.find({
|
|
where: { gameid: gameId },
|
|
order: { turnNumber: 'ASC', createdat: 'ASC' }
|
|
});
|
|
}
|
|
|
|
async findByGameAndTrigger(gameId: string, trigger: SnapshotTrigger): Promise<GameSnapshotAggregate[]> {
|
|
return await this.repository.find({
|
|
where: {
|
|
gameid: gameId,
|
|
trigger: trigger
|
|
},
|
|
order: { createdat: 'DESC' }
|
|
});
|
|
}
|
|
|
|
async findByGameAndTurn(gameId: string, turnNumber: number): Promise<GameSnapshotAggregate | null> {
|
|
return await this.repository.findOne({
|
|
where: {
|
|
gameid: gameId,
|
|
turnNumber: turnNumber
|
|
},
|
|
order: { createdat: 'DESC' }
|
|
});
|
|
}
|
|
|
|
async deleteOldSnapshots(gameId: string, keepCount: number): Promise<void> {
|
|
const snapshots = await this.repository.find({
|
|
where: { gameid: gameId },
|
|
order: { createdat: 'DESC' },
|
|
select: ['id', 'createdat']
|
|
});
|
|
|
|
if (snapshots.length > keepCount) {
|
|
const idsToDelete = snapshots
|
|
.slice(keepCount)
|
|
.map(s => s.id);
|
|
|
|
if (idsToDelete.length > 0) {
|
|
await this.repository.delete(idsToDelete);
|
|
}
|
|
}
|
|
}
|
|
|
|
async deleteByGameId(gameId: string): Promise<void> {
|
|
await this.repository.delete({ gameid: gameId });
|
|
}
|
|
}
|