76 lines
2.9 KiB
TypeScript
76 lines
2.9 KiB
TypeScript
import { logger } from "@/lib/logger";
|
|
import type { Match, MatchInput } from "@/features/matches/types";
|
|
import type PocketBase from "pocketbase";
|
|
import { transformMatch } from "../util/transform-types";
|
|
|
|
export function createMatchesService(pb: PocketBase) {
|
|
return {
|
|
async getMatch(id: string): Promise<Match | null> {
|
|
const result = await pb.collection("matches").getOne(id, {
|
|
expand: "tournament, home, away",
|
|
});
|
|
return transformMatch(result);
|
|
},
|
|
|
|
// match Ids where the current lid is home_from_lid or away_from_lid
|
|
async getChildMatches(matchId: string): Promise<{ winner: Match | undefined, loser: Match | undefined }> {
|
|
const match = await this.getMatch(matchId);
|
|
if (!match) throw new Error("Match not found")
|
|
|
|
const result = await pb.collection("matches").getFullList({
|
|
filter: `tournament="${match.tournament.id}" && (home_from_lid = ${match.lid} || away_from_lid = ${match.lid}) && bye = false`,
|
|
expand: "tournament, home, away",
|
|
});
|
|
|
|
const winnerMatch = result.find(m => (m.home_from_lid === match.lid && !m.home_from_loser) || (m.away_from_lid === match.lid && !m.away_from_loser));
|
|
const loserMatch = result.find(m => (m.home_from_lid === match.lid && m.home_from_loser) || (m.away_from_lid === match.lid && m.away_from_loser));
|
|
|
|
return {
|
|
winner: winnerMatch ? transformMatch(winnerMatch) : undefined,
|
|
loser: loserMatch ? transformMatch(loserMatch) : undefined
|
|
}
|
|
},
|
|
|
|
async createMatch(data: MatchInput): Promise<Match> {
|
|
logger.info("PocketBase | Creating match", data);
|
|
const result = await pb.collection("matches").create<Match>(data);
|
|
return result;
|
|
},
|
|
|
|
async createMatches(matches: MatchInput[]): Promise<Match[]> {
|
|
logger.info("PocketBase | Creating multiple matches", {
|
|
count: matches.length,
|
|
});
|
|
const results = await Promise.all(
|
|
matches.map((match) => pb.collection("matches").create<Match>(match))
|
|
);
|
|
return results;
|
|
},
|
|
|
|
async updateMatch(id: string, data: Partial<MatchInput>): Promise<Match> {
|
|
logger.info("PocketBase | Updating match", { id, data });
|
|
const result = await pb.collection("matches").update<Match>(id, data, {
|
|
expand: 'home, away, tournament'
|
|
});
|
|
return transformMatch(result);
|
|
},
|
|
|
|
async deleteMatch(id: string): Promise<void> {
|
|
logger.info("PocketBase | Deleting match", id);
|
|
await pb.collection("matches").delete(id);
|
|
},
|
|
|
|
async deleteMatchesByTournament(tournamentId: string): Promise<void> {
|
|
logger.info("PocketBase | Deleting matches for tournament", tournamentId);
|
|
const matches = await pb.collection("matches").getFullList({
|
|
filter: `tournament = "${tournamentId}"`,
|
|
fields: "id",
|
|
});
|
|
|
|
await Promise.all(
|
|
matches.map((match) => pb.collection("matches").delete(match.id))
|
|
);
|
|
},
|
|
};
|
|
}
|