Skip to content

Commit

Permalink
refactor: simplify treatment selection service
Browse files Browse the repository at this point in the history
  • Loading branch information
sgfost committed Sep 12, 2023
1 parent 36d8f13 commit e59c804
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions server/src/services/sologame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,23 @@ export class SoloGameService extends BaseService {
* get the next treatment (in order) that a user has not yet seen. If they have seen all
* then return a random one.
*/
const numTreatments = await this.em.getRepository(SoloGameTreatment).count();
const playedTreatments = await this.em
.getRepository(User)
.createQueryBuilder("user")
.leftJoin("user.soloPlayers", "soloPlayer")
.leftJoin("soloPlayer.game", "soloGame")
.select("soloGame.treatmentId as treatment")
.where("user.id = :userId", { userId })
.getRawMany();

const playedTreatmentIds = new Set(playedTreatments.map(pt => pt.treatment));
const treatmentRepo = this.em.getRepository(SoloGameTreatment);
if (playedTreatmentIds.size < numTreatments) {
for (let i = 1; i <= numTreatments; i++) {
if (!playedTreatmentIds.has(i)) {
return treatmentRepo.findOneOrFail(i);
}
}
const numTreatments = await treatmentRepo.count();

const highestPlayedTreatment = (
await this.em
.getRepository(User)
.createQueryBuilder("user")
.leftJoin("user.soloPlayers", "soloPlayer")
.leftJoin("soloPlayer.game", "soloGame")
.select("COALESCE(MAX(soloGame.treatmentId), 0)", "max")
.where("user.id = :userId", { userId })
.getRawOne()
).max;

if (highestPlayedTreatment < numTreatments) {
return treatmentRepo.findOneOrFail(highestPlayedTreatment + 1);
}

return treatmentRepo.findOneOrFail(getRandomIntInclusive(1, numTreatments));
}

Expand Down

0 comments on commit e59c804

Please sign in to comment.