Skip to content

Commit

Permalink
deps(WIP): upgrade typeorm to 0.3.20, fix API breaking changes
Browse files Browse the repository at this point in the history
https://typeorm.io/changelog#breaking-changes-2

this commit addresses find(), findOne(), and similar methods changes

TODO: migrate from manager/connection to DataSource
(https://typeorm.io/changelog#deprecations)

[no ci]
  • Loading branch information
sgfost committed Feb 2, 2024
1 parent 63ba13a commit 3593add
Show file tree
Hide file tree
Showing 13 changed files with 815 additions and 356 deletions.
1,018 changes: 726 additions & 292 deletions server/package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"ts-node": "^10.7.0",
"ts-node-dev": "^2.0.0",
"tsconfig-paths": "^4.0.0",
"typeorm-fixtures-cli": "^1.9.0",
"typeorm-fixtures-cli": "^4.0.0",
"typescript": "^4.6.4",
"yamljs": "^0.3.0"
},
Expand Down Expand Up @@ -111,7 +111,7 @@
"redis": "^3.1.1",
"reflect-metadata": "^0.1.10",
"tinyqueue": "^2.0.3",
"typeorm": "^0.2.30",
"typeorm": "^0.3.20",
"uuid": "^8.3.2",
"validator": "^13.5.2"
},
Expand Down
12 changes: 9 additions & 3 deletions server/src/entity/TournamentRoundSignup.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { Entity, ManyToOne } from "typeorm";
import { Entity, ManyToOne, PrimaryColumn } from "typeorm";
import { TournamentRoundInvite } from "./TournamentRoundInvite";
import { TournamentRoundDate } from "./TournamentRoundDate";

@Entity()
export class TournamentRoundSignup {
@ManyToOne(type => TournamentRoundInvite, invite => invite.signups, { primary: true })
@PrimaryColumn()
tournamentRoundInviteId!: number;

@ManyToOne(() => TournamentRoundInvite, invite => invite.signups)
tournamentRoundInvite!: TournamentRoundInvite;

@ManyToOne(type => TournamentRoundDate, date => date.signups, { primary: true })
@PrimaryColumn()
tournamentRoundDateId!: number;

@ManyToOne(() => TournamentRoundDate, date => date.signups)
tournamentRoundDate!: TournamentRoundDate;
}
26 changes: 12 additions & 14 deletions server/src/services/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export class AccountService extends BaseService {
}

async findByUsername(username: string): Promise<User> {
return await this.getRepository().findOneOrFail({ username });
return await this.getRepository().findOneByOrFail({ username });
}

async findUsers(usernames: Array<string>): Promise<Array<User>> {
Expand All @@ -117,15 +117,15 @@ export class AccountService extends BaseService {
}

async isEmailAvailable(user: User, email: string): Promise<boolean> {
const otherUser = await this.getRepository().findOne({ email });
const otherUser = await this.getRepository().findOneBy({ email });
if (otherUser) {
return otherUser.id === user.id;
}
return true;
}

async isUsernameAvailable(username: string, user?: User): Promise<boolean> {
const otherUser = await this.getRepository().findOne({ username });
const otherUser = await this.getRepository().findOneBy({ username });
if (otherUser) {
if (!user) {
return false;
Expand Down Expand Up @@ -166,20 +166,20 @@ export class AccountService extends BaseService {
}

async findUserById(id: number): Promise<User> {
return await this.getRepository().findOneOrFail(id);
return await this.getRepository().findOneByOrFail({ id });
}

async denyConsent(id: number): Promise<ClientSafeUser> {
const repo = this.getRepository();
const user = await repo.findOneOrFail(id);
const user = await repo.findOneByOrFail({ id });
user.dateConsented = undefined;
await repo.save(user);
return toClientSafeUser(user);
}

async grantConsent(id: number): Promise<ClientSafeUser> {
const repo = this.getRepository();
const user = await repo.findOneOrFail(id);
const user = await repo.findOneByOrFail({ id });
user.dateConsented = new Date();
await repo.save(user);
return toClientSafeUser(user);
Expand Down Expand Up @@ -283,10 +283,8 @@ export class AccountService extends BaseService {
return;
}

async findUnregisteredUserByRegistrationToken(
registrationToken: string
): Promise<User | undefined> {
return await this.em.getRepository(User).findOne({ registrationToken });
async findUnregisteredUserByRegistrationToken(registrationToken: string): Promise<User | null> {
return await this.em.getRepository(User).findOneBy({ registrationToken });
}

async verifyUnregisteredUser(u: User, registrationToken: string): Promise<UpdateResult> {
Expand Down Expand Up @@ -327,7 +325,7 @@ export class AccountService extends BaseService {
}

async getOrCreateTestUser(username: string, shouldSkipVerification = true): Promise<User> {
let user = await this.getRepository().findOne({ username });
let user = await this.getRepository().findOneBy({ username });
if (!user) {
user = new User();
user.username = username;
Expand All @@ -347,14 +345,14 @@ export class AccountService extends BaseService {
}

async getOrCreateUser(userData: { email: string; passportId?: string }): Promise<User> {
let user: User | undefined;
let user: User | null = null;
// try to find user by id
if (userData.passportId) {
user = await this.getRepository().findOne({ passportId: userData.passportId });
user = await this.getRepository().findOneBy({ passportId: userData.passportId });
}
// if no id or find by id turned up empty, try to find user by email
if (!userData.passportId || !user) {
user = await this.getRepository().findOne({ email: userData.email });
user = await this.getRepository().findOneBy({ email: userData.email });
}
if (!user) {
user = new User();
Expand Down
6 changes: 3 additions & 3 deletions server/src/services/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export class AdminService extends BaseService {
async takeModerationAction(data: ModerationActionData) {
const moderationActionRepo = this.em.getRepository(ModerationAction);
const reportRepo = this.em.getRepository(ChatReport);
const report = await reportRepo.findOneOrFail({ id: data.reportId });
const report = await reportRepo.findOneByOrFail({ id: data.reportId });
const user = await this.sp.account.findByUsername(data.username);
const admin = await this.sp.account.findByUsername(data.adminUsername);
const { username, adminUsername, ...moderationActionData } = data;
Expand Down Expand Up @@ -187,10 +187,10 @@ export class AdminService extends BaseService {
async undoModerationAction(data: { moderationActionId: number; username: string }) {
const moderationActionRepo = this.em.getRepository(ModerationAction);
const reportRepo = this.em.getRepository(ChatReport);
const moderationAction = await moderationActionRepo.findOneOrFail({
const moderationAction = await moderationActionRepo.findOneByOrFail({
id: data.moderationActionId,
});
const report = await reportRepo.findOneOrFail({ id: moderationAction.reportId });
const report = await reportRepo.findOneByOrFail({ id: moderationAction.reportId });
// mark moderationAction as revoked
moderationAction.revoked = true;
await moderationActionRepo.save(moderationAction);
Expand Down
6 changes: 4 additions & 2 deletions server/src/services/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { IsNull } from "typeorm";

export class GameService extends BaseService {
async findById(id: number): Promise<Game> {
return await this.em.getRepository(Game).findOneOrFail(id);
return await this.em.getRepository(Game).findOneByOrFail({ id });
}

async findByRoomId(roomId: string): Promise<Game> {
Expand All @@ -16,7 +16,9 @@ export class GameService extends BaseService {

async getTotalActiveGames(): Promise<number> {
return await this.em.getRepository(Game).count({
dateFinalized: IsNull(),
where: {
dateFinalized: IsNull(),
},
});
}

Expand Down
4 changes: 2 additions & 2 deletions server/src/services/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,14 @@ export class DBPersister implements Persister {
where: { type: In(DBPersister.FINAL_EVENTS), gameId },
order: { id: "DESC", dateCreated: "DESC" },
});
const game = await em.getRepository(Game).findOneOrFail(gameId);
const game = await em.getRepository(Game).findOneByOrFail({ id: gameId });
game.status = event.type === "entered-defeat-phase" ? "defeat" : "victory";
game.dateFinalized = this.sp.time.now();
if (!shouldFinalizePlayers) {
const res: [Game, Array<Player>] = [await em.save(game), []];
return res;
}
const players = await em.getRepository(Player).find({ gameId });
const players = await em.getRepository(Player).findBy({ gameId });
for (const p of players) {
p.points = (event.payload as any)[p.role];
}
Expand Down
12 changes: 6 additions & 6 deletions server/src/services/quiz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class QuizService extends BaseService {
await this.em.getRepository(QuestionResponse).save(questionResponse);
questionResponse.question = await this.em
.getRepository(Question)
.findOneOrFail({ id: questionId });
.findOneByOrFail({ id: questionId });
return questionResponse;
}

Expand All @@ -40,8 +40,8 @@ export class QuizService extends BaseService {
async findQuizSubmission(
id: number,
opts?: FindOneOptions<QuizSubmission>
): Promise<QuizSubmission | undefined> {
return this.em.getRepository(QuizSubmission).findOne(id, opts);
): Promise<QuizSubmission | null> {
return this.em.getRepository(QuizSubmission).findOneBy({ ...opts, id });
}

async getDefaultQuiz(opts?: FindOneOptions<Quiz>): Promise<Quiz> {
Expand All @@ -50,7 +50,7 @@ export class QuizService extends BaseService {
}

async getQuizById(id: number, opts?: FindOneOptions<Quiz>): Promise<Quiz> {
return await this.em.getRepository(Quiz).findOneOrFail(id, opts);
return await this.em.getRepository(Quiz).findOneByOrFail({ ...opts, id });
}

async getQuizByName(name: string, opts?: FindOneOptions<Quiz>): Promise<Quiz> {
Expand All @@ -65,7 +65,7 @@ export class QuizService extends BaseService {
userId: number,
quizId: number,
opts: FindOneOptions<QuizSubmission> = {}
): Promise<QuizSubmission | undefined> {
): Promise<QuizSubmission | null> {
opts = { order: { dateCreated: "DESC" }, ...opts };
return await this.em
.getRepository(QuizSubmission)
Expand All @@ -82,7 +82,7 @@ export class QuizService extends BaseService {
}

async findQuestion(id: number): Promise<Question> {
return await this.em.getRepository(Question).findOneOrFail(id);
return await this.em.getRepository(Question).findOneByOrFail({ id });
}

async isCorrect(questionResponse: QuestionResponse): Promise<boolean> {
Expand Down
17 changes: 10 additions & 7 deletions server/src/services/sologame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@ export class SoloGameService extends BaseService {
).max;

if (highestPlayedTreatment < numTreatments) {
return treatmentRepo.findOneOrFail(highestPlayedTreatment + 1);
return treatmentRepo.findOneByOrFail({ id: highestPlayedTreatment + 1 });
}
return treatmentRepo.findOneOrFail(getRandomIntInclusive(1, numTreatments));
return treatmentRepo.findOneByOrFail({ id: getRandomIntInclusive(1, numTreatments) });
}

async getTreatmentById(id: number): Promise<TreatmentData> {
return this.em.getRepository(SoloGameTreatment).findOneOrFail(id);
return this.em.getRepository(SoloGameTreatment).findOneByOrFail({ id });
}

async createGame(state: SoloGameState): Promise<SoloGame> {
Expand All @@ -103,7 +103,10 @@ export class SoloGameService extends BaseService {
await gameRepo.save(game);
player.gameId = game.id;
await playerRepo.save(player);
return gameRepo.findOneOrFail(game.id, { relations: ["deck", "deck.cards"] });
return gameRepo.findOneOrFail({
where: { id: game.id },
relations: ["deck", "deck.cards"],
});
}

async createPlayer(userId: number): Promise<SoloPlayer> {
Expand Down Expand Up @@ -147,7 +150,7 @@ export class SoloGameService extends BaseService {

async updateGameStatus(gameId: number, status: SoloGameStatus) {
const repo = this.em.getRepository(SoloGame);
const game = await repo.findOneOrFail(gameId);
const game = await repo.findOneByOrFail({ id: gameId });
game.status = status;
await repo.save(game);
}
Expand All @@ -159,7 +162,7 @@ export class SoloGameService extends BaseService {
status: SoloGameStatus
) {
const repo = this.em.getRepository(SoloPlayer);
const player = await repo.findOneOrFail({ gameId });
const player = await repo.findOneByOrFail({ gameId });
player.points = points;
await repo.save(player);
// if the game was a success, update the player's highscore table as well
Expand Down Expand Up @@ -197,7 +200,7 @@ export class SoloGameService extends BaseService {
// additionally, set the round on all cards that were drawn this round
const cards = state.roundEventCards;
for (const card of cards) {
const deckCard = await deckCardRepo.findOneOrFail({ id: card.deckCardId });
const deckCard = await deckCardRepo.findOneByOrFail({ id: card.deckCardId });
if (deckCard) {
deckCard.round = round;
await deckCardRepo.save(deckCard);
Expand Down
39 changes: 26 additions & 13 deletions server/src/services/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,29 @@ import { SoloHighScore } from "@port-of-mars/server/entity/SoloHighScore";

export class StatsService extends BaseService {
/* Player stats */
async getGamesWithUser(user: User): Promise<Array<Game>> {
return this.em.getRepository(Game).find({
join: { alias: "games", innerJoin: { players: "games.players" } },
where: (qb: SelectQueryBuilder<Game>) => {
qb.where({ dateFinalized: Not(IsNull()) }).andWhere("players.user.id = :userId", {
userId: user.id,
});
},
relations: ["players"],
order: { dateCreated: "DESC" },
});
// async getGamesWithUser(user: User): Promise<Array<Game>> {
// return this.em.getRepository(Game).find({
// join: { alias: "games", innerJoin: { players: "games.players" } },
// where: (qb: SelectQueryBuilder<Game>) => {
// qb.where({ dateFinalized: Not(IsNull()) }).andWhere("players.user.id = :userId", {
// userId: user.id,
// });
// },
// relations: ["players"],
// order: { dateCreated: "DESC" },
// });
// }
// TODO: verify this
async getGamesWithUser(user: User): Promise<Game[]> {
const games = await this.em
.createQueryBuilder(Game, "game")
.innerJoin("game.players", "player")
.where("game.dateFinalized IS NOT NULL")
.andWhere("player.userId = :userId", { userId: user.id })
.orderBy("game.dateCreated", "DESC")
.getMany();

return games;
}

async getPlayerHistory(user: User): Promise<Array<PlayerStatItem>> {
Expand Down Expand Up @@ -112,11 +124,12 @@ export class StatsService extends BaseService {
// update the solo highscores table with data from a victory game and return the player's entry with rank
const highscoreRepo = this.em.getRepository(SoloHighScore);
const pointsPerRound = points / maxRound;
const game = await this.em.getRepository(SoloGame).findOneOrFail(gameId, {
const game = await this.em.getRepository(SoloGame).findOneOrFail({
where: { id: gameId },
relations: ["player", "player.user"],
});
const user = game.player.user;
let highscore = await highscoreRepo.findOne({ user });
let highscore = await highscoreRepo.findOneBy({ user });

if (highscore) {
if (pointsPerRound > highscore.pointsPerRound) {
Expand Down
7 changes: 4 additions & 3 deletions server/src/services/survey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@ export class SurveyService extends BaseService {
}

async setSurveyComplete(data: { inviteId: number; surveyId: string }) {
const invite = await this.em
.getRepository(TournamentRoundInvite)
.findOneOrFail(data.inviteId, { relations: ["user", "tournamentRound"] });
const invite = await this.em.getRepository(TournamentRoundInvite).findOneOrFail({
where: { id: data.inviteId },
relations: ["user", "tournamentRound"],
});
const tournamentRound = invite.tournamentRound;
const introSurveyUrl = tournamentRound.introSurveyUrl;
const exitSurveyUrl = tournamentRound.exitSurveyUrl;
Expand Down
Loading

0 comments on commit 3593add

Please sign in to comment.