Add validation for maxTeams amount and refresh Team count properly
This commit is contained in:
@@ -199,6 +199,12 @@ app.post('/tournaments/:id/teams', authMiddleware, async (req: Request, res: Res
|
||||
const entry = await teamService.registerTeamForTournament(+req.params.id, +teamId);
|
||||
res.status(201).send(entry);
|
||||
} catch (err: any) {
|
||||
if (err.message === 'Turnier nicht gefunden') {
|
||||
return res.status(404).send({error: err.message});
|
||||
}
|
||||
if (err.message === 'Das Turnier hat bereits die maximale Anzahl an Teams erreicht') {
|
||||
return res.status(409).send({error: err.message});
|
||||
}
|
||||
if (err.message?.includes('UNIQUE constraint failed')) {
|
||||
return res.status(409).send({error: 'Das Team ist bereits für dieses Turnier angemeldet'});
|
||||
}
|
||||
|
||||
@@ -145,19 +145,38 @@ export class TeamService {
|
||||
|
||||
registerTeamForTournament(tournamentId: number, teamId: number): Promise<TournamentTeam> {
|
||||
return new Promise<TournamentTeam>((resolve, reject) => {
|
||||
const stmt = this.db.prepare(
|
||||
`INSERT INTO TournamentTeams (tournamentId, teamId) VALUES (?, ?)`
|
||||
this.db.get(
|
||||
`SELECT t.maxTeamAmount as maxTeamAmount,
|
||||
COUNT(tt.id) as currentTeamAmount
|
||||
FROM Tournaments t
|
||||
LEFT JOIN TournamentTeams tt ON t.id = tt.tournamentId
|
||||
WHERE t.id = ?
|
||||
GROUP BY t.id`,
|
||||
[tournamentId],
|
||||
(err: Error | null, row: any) => {
|
||||
if (err) return reject(err);
|
||||
if (!row) {
|
||||
return reject(new Error('Turnier nicht gefunden'));
|
||||
}
|
||||
if (row.currentTeamAmount >= row.maxTeamAmount) {
|
||||
return reject(new Error('Das Turnier hat bereits die maximale Anzahl an Teams erreicht'));
|
||||
}
|
||||
|
||||
const stmt = this.db.prepare(
|
||||
`INSERT INTO TournamentTeams (tournamentId, teamId) VALUES (?, ?)`
|
||||
);
|
||||
stmt.run(tournamentId, teamId, function (this: RunResult, err: Error | null) {
|
||||
if (err) return reject(err);
|
||||
resolve({
|
||||
id: (this as any).lastID,
|
||||
tournamentId,
|
||||
teamId,
|
||||
registeredAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
stmt.finalize();
|
||||
}
|
||||
);
|
||||
stmt.run(tournamentId, teamId, function (this: RunResult, err: Error | null) {
|
||||
if (err) return reject(err);
|
||||
resolve({
|
||||
id: (this as any).lastID,
|
||||
tournamentId,
|
||||
teamId,
|
||||
registeredAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
stmt.finalize();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user