Skip to content

Commit

Permalink
Add comments and documentation for clarity; mark deprecated components (
Browse files Browse the repository at this point in the history
  • Loading branch information
tydolla00 authored Jan 15, 2025
1 parent a4cb67e commit e1f77c7
Show file tree
Hide file tree
Showing 30 changed files with 281 additions and 465 deletions.
8 changes: 8 additions & 0 deletions prisma/lib/admin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { unstable_cache } from "next/cache";
import prisma from "../db";

/**
* Retrieves all video sessions from the database, including the associated game names.
*
* This function uses `unstable_cache` to cache the results for 1 week (604800 seconds).
* The cache is tagged with "getAllSessions" for easy invalidation.
*
* @returns {Promise<Array>} A promise that resolves to an array of video sessions with game names.
*/
export const getAllSessions = unstable_cache(
async () =>
await prisma.videoSession.findMany({
Expand Down
51 changes: 35 additions & 16 deletions prisma/lib/games.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ import { getSumOfStat } from "@prisma/client/sql";
// Cache is used for deduping
// unstable is used for time based caching
// perks of using this method is we can invalidate certain paths.

/**
* Fetches all games from the database.
* @returns all game records including gameName and gameId
* Retrieves all games from the database.
*
* This function uses the `unstable_cache` to cache the results of the database query.
* The cache is tagged with "getAllGames" and does not revalidate.
*
* @returns {Promise<Game[]>} A promise that resolves to an array of games.
*/
export const getAllGames = unstable_cache(
async () => await prisma.game.findMany(),
Expand All @@ -21,13 +26,23 @@ export const getAllGames = unstable_cache(
},
);

/**
* Retrieves the sum of a specific statistic for a given player.
*
* @param playerId - The unique identifier of the player.
* @param statName - The name of the statistic to sum.
* @returns A promise that resolves to the sum of the specified statistic for the player.
*/
export const getSumPerStat = async (playerId: number, statName: StatName) =>
await prisma.$queryRawTyped(getSumOfStat(playerId, statName));

/**
* Fetches all sets pertaining to a game from the database.
* @param gameId id of the game record
* @returns Data about a game's sets.
* Retrieves the sets associated with a specific player in a game.
*
* @deprecated
* @param {number} gameId - The unique identifier of the game.
* @returns {Promise<Array>} A promise that resolves to an array of video sessions,
* each containing the count of sets and their associated matches.
*/
export const getSetsPerPlayer = async (gameId: number) =>
await prisma.videoSession.findMany({
Expand All @@ -36,9 +51,10 @@ export const getSetsPerPlayer = async (gameId: number) =>
});

/**
* Fetches all records for a game including info about the winners of the session, set, and match.
* @param gameId id of the game record
* @returns all records for a game
* Retrieves the wins per player for a given game.
*
* @param {number} gameId - The unique identifier of the game.
* @returns {Promise<object | null>} A promise that resolves to an object containing the sessions and their respective match winners and set winners, or null if no game is found.
*/
export const getWinsPerPlayer = async (gameId: number) =>
await prisma.game.findFirst({
Expand All @@ -60,10 +76,12 @@ export const getWinsPerPlayer = async (gameId: number) =>
});

/**
* Fetches all sessions for a game and includes the player sessions and matches. Useful for calculating info per match/session.
* @param gameId id of the game record
* @param statName StatName of the stat you are checking for, must end in _POS for now.
* @returns all player records with a given StatName
* Retrieves matches per game based on the provided game ID and stat name. It is useful for calculating player stats per match.
*
* @template T - The type of the stat name, extending from `StatName`.
* @param {number} gameId - The ID of the game to retrieve matches for.
* @param {StatEndsWith<"POS", T>} statName - The stat name ending with "POS" to filter player stats.
* @returns {Promise<Array>} A promise that resolves to an array of video sessions with nested sets, matches, and player sessions.
*/
export const getMatchesPerGame = async <T extends StatName = StatName>(
gameId: number,
Expand Down Expand Up @@ -97,10 +115,11 @@ export const getMatchesPerGame = async <T extends StatName = StatName>(
});

/**
* Fetches all player records for a game for a given statname.
* @param gameId id of the game record
* @param statName Statname of the stat you are checking for.
* @returns Array of play records
* Retrieves statistics for each player in a specific game. The statistics are filtered by the provided statistic name.
*
* @param gameId - The unique identifier of the game.
* @param statName - The name of the statistic to retrieve.
* @returns A promise that resolves to an array of player statistics, including the player and the value of the statistic.
*/
export const getStatPerPlayer = async (gameId: number, statName: StatName) =>
await prisma.playerStat.findMany({
Expand Down
8 changes: 8 additions & 0 deletions prisma/lib/members.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import prisma from "../db";
import { unstable_cache } from "next/cache";

/**
* Retrieves all members from the database.
*
* This function uses the `unstable_cache` to cache the results of the database query.
* The cache is tagged with "allMembers" and does not revalidate.
*
* @returns {Promise<Array<Player>>} A promise that resolves to an array of player objects.
*/
export const getAllMembers = unstable_cache(
async () => {
return await prisma.player.findMany();
Expand Down
1 change: 1 addition & 0 deletions prisma/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Keep in sync with the seed script in prisma/seed.ts
export enum StatNames {
MarioKartPosition = "MK8_POS",
MarioKartDays = "MK8_DAY",
Expand Down
133 changes: 0 additions & 133 deletions prisma/scripts/testbed.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,9 @@
import prisma from "../db";
import { EnrichedSession } from "../types/session";
import { EnrichedGameSet } from "../types/gameSet";

async function main() {
console.log(await getAllTimeMKRankings());
}

/// Fetched Enriched Mario Kart Session
async function getLatestMarioKartSession() {
try {
const latestMKPlayerSessions = await prisma.videoSession.findFirst({
where: {
gameId: 1,
},
orderBy: {
sessionId: "desc",
},
include: {
sets: {
include: {
matches: {
include: {
playerSessions: {
include: {
playerStats: true,
},
},
},
},
},
},
},
});
if (latestMKPlayerSessions != null) {
console.log("Latest Mario Kart Session: ", [latestMKPlayerSessions]);
console.log("Set 1: ", showSetResults(latestMKPlayerSessions.sets[0]));
}
} catch (error) {
console.error("Error Fetching Latest Mario Kart Session");
}
}

// /**
// * Takes a mario kart set and prints out the stats for each player.
// * Format:
// * Player: playerName
// * Rankings: []number
// * @param mkSession
// */
async function showSetResults(mkSet: EnrichedGameSet) {
for (const match of mkSet.matches) {
console.log("Looking at match: ", match);
for (const playerSession of match.playerSessions) {
console.log(
`Looking at PlayerSession: , ${playerSession} for ${playerSession.player}`,
);
console.log(
`Player Stats: ${playerSession.playerStats.map((stat) => stat.value).join(", ")}`,
);
}
}
}

async function getAllTimeMKRankings() {
const playerStats = await prisma.playerStat.findMany({
where: {
Expand All @@ -79,81 +21,6 @@ async function getAllTimeMKRankings() {
console.log("Player Stats", playerStats);
}

// ! TODO Can we remove this?
// async function showSetStatsByPlayerByRace(mkSession: EnrichedSession[]) {
// // Group Stats For A Set By Player
// for (const session of mkSession) {
// for (const set of session.sets) {
// console.log(`--- Set ${set.setId} ---`);
// const playerStatsMap: { [playerName: string]: string[] } = {};

// for (const playerSession of set.playerSessions) {
// const playerName = playerSession.player.playerName;
// if (!playerStatsMap[playerName]) {
// playerStatsMap[playerName] = [];
// }
// for (const playerStat of playerSession.playerStats) {
// playerStatsMap[playerName].push(playerStat.value);
// }
// }

// for (const playerName in playerStatsMap) {
// console.log(`\nPlayer: ${playerName}`);
// console.log(`Placements: ${playerStatsMap[playerName].join(", ")}`);
// }
// console.log(getMK8RankingsFromSet(set));
// }
// }
// }

/**
/* Given a MK8 Set, return the rankings for each player and the number of points they received
* @param set
* @returns
*/
// async function getMK8RankingsFromSet(set: EnrichedGameSet) {
// const pointsMap = [6, 4, 3, 2, 1];
// const playerPoints: { [playerName: string]: number } = {
// Mark: 0,
// Dylan: 0,
// Ben: 0,
// Lee: 0,
// Des: 0,
// };

// // Leaving these comments logs in for debugging purposes TODO: Remove when done
// for (const playerSession of set.playerSessions) {
// // console.log(`Looking at PlayerSession ${playerSession.playerSessionId}`);

// const playerName = playerSession.player.playerName;

// for (const playerStat of playerSession.playerStats) {
// // console.log(`\nLooking at statId${playerStat.statId}`);

// const placement = parseInt(playerStat.value);
// // console.log(
// // `${playerName} placed ${placement} and received ${pointsMap[placement - 1]} points`,
// // );
// if (placement >= 1 && placement <= 5) {
// const pointsWon = pointsMap[placement - 1];
// // console.log(`Points Won: ${pointsWon}`);
// playerPoints[playerName] += pointsWon;
// // console.log("Player Points: ", playerPoints);
// }
// }
// // }

// const rankings = Object.entries(playerPoints)
// .sort(([, pointsA], [, pointsB]) => pointsB - pointsA)
// .map(([playerName, points], index) => ({
// rank: index + 1,
// playerName,
// points,
// }));

// return rankings;
// }

main()
.then(async () => {
await prisma.$disconnect();
Expand Down
15 changes: 1 addition & 14 deletions src/app/(routes)/(groups)/members/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,10 @@ import { getAllMembers } from "../../../../../../prisma/lib/members";

export const dynamicParams = false; // true | false,

const membersObj = {
lee: "leland",
mark: "mark",
dylan: "dylan",
ben: "ben",
des: "des",
john: "john",
aff: "aff",
ippi: "ippi",
} as const;

export async function generateStaticParams() {
const members = await getAllMembers();
return members.map((member) => ({
slug: membersObj[
member.playerName.toLowerCase() as keyof typeof membersObj
],
slug: member.playerName.toLowerCase(),
}));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import useViewTransition from "@/hooks/useViewTransition";
import Image from "next/image";
import { useState } from "react";

// Deprecated
export const Members3D = () => {
const members = [
"https://static.wikia.nocookie.net/rdcworld1/images/f/f2/Mark-Phillips.jpg/revision/latest/thumbnail/width/360/height/450?cb=20191004005953",
Expand Down
2 changes: 0 additions & 2 deletions src/app/(routes)/(groups)/members/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@ import {
HoverCardTrigger,
} from "@/components/ui/hover-card";
import { RDCMembers } from "@/lib/constants";
import { Members3D } from "./_client/interactive-members";

// TODO Revalidate Stats Once Per Week
// TODO Show all button that displays all Members. Default is centered 3D circular card that pops up from the 'ground'

export default async function Page() {
const members = Array.from(RDCMembers.entries());
// return <Members3D />;
return (
<div className="m-16">
<H1>Members</H1>
Expand Down
Loading

0 comments on commit e1f77c7

Please sign in to comment.