Skip to content

Commit

Permalink
Merge pull request #41 from tobyrushton/fix/playoffs
Browse files Browse the repository at this point in the history
fix: fix error caused by playoffs
  • Loading branch information
tobyrushton authored Apr 18, 2024
2 parents 1a9e624 + df7f55c commit 0b75bc1
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 63 deletions.
3 changes: 3 additions & 0 deletions __tests__/server/routers/getRecord.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ describe('api/getRecord', () => {
opponent_score: {
not: -1,
},
type: 'REGULAR',
},
})

Expand All @@ -61,6 +62,7 @@ describe('api/getRecord', () => {
opponent_score: {
not: -1,
},
type: 'REGULAR',
},
})

Expand Down Expand Up @@ -101,6 +103,7 @@ describe('api/getRecord', () => {
opponent_score: {
not: -1,
},
type: 'REGULAR',
},
})
expect(record).toEqual({ wins: 2, losses: 1 })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- CreateEnum
CREATE TYPE "GameType" AS ENUM ('REGULAR', 'PLAYOFF', 'PRESEASON');

-- AlterTable
ALTER TABLE "Game" ADD COLUMN "type" "GameType" NOT NULL DEFAULT 'REGULAR';
15 changes: 11 additions & 4 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

generator client {
provider = "prisma-client-js"
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
binaryTargets = ["native","rhel-openssl-1.0.x"]
binaryTargets = ["native", "rhel-openssl-1.0.x"]
}

model Player {
Expand Down Expand Up @@ -91,4 +91,11 @@ model Game {
opponent_score Int
home_score Int
PlayerGame PlayerGame[]
type GameType @default(REGULAR)
}

enum GameType {
REGULAR
PLAYOFF
PRESEASON
}
82 changes: 44 additions & 38 deletions src/components/NextGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,46 +47,52 @@ export const NextGame: FC = async () => {
<Card className="h-min">
<CardHeader>
<CardTitle>
<NextGameTime
nextGameTime={nextGame[0].date.toISOString()}
/>
{nextGame.length > 0 ? (
<NextGameTime
nextGameTime={nextGame[0].date.toISOString()}
/>
) : (
'No upcoming games'
)}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-row">
<div className="flex grow justify-center">
<Link
className="flex flex-col gap-5"
href={`/team/${team.id}`}
>
<Image
src={team.logo_url}
alt={`${team.name} logo`}
width={100}
height={100}
className="self-center"
/>
{team.name}
</Link>
</div>
<p className="flex flex-wrap content-center">
{nextGame[0].home ? 'vs' : '@'}
</p>
<div className="flex grow justify-center">
<Link
className="flex flex-col gap-5"
href={`/team/${nextGame[0].opponent.id}`}
>
<Image
src={nextGame[0].opponent.logo_url}
alt={`${nextGame[0].opponent.name} logo`}
width={100}
height={100}
className="self-center"
/>
{nextGame[0].opponent.name}
</Link>
</div>
</CardContent>
{nextGame.length > 0 && (
<CardContent className="flex flex-row">
<div className="flex grow justify-center">
<Link
className="flex flex-col gap-5"
href={`/team/${team.id}`}
>
<Image
src={team.logo_url}
alt={`${team.name} logo`}
width={100}
height={100}
className="self-center"
/>
{team.name}
</Link>
</div>
<p className="flex flex-wrap content-center">
{nextGame[0].home ? 'vs' : '@'}
</p>
<div className="flex grow justify-center">
<Link
className="flex flex-col gap-5"
href={`/team/${nextGame[0].opponent.id}`}
>
<Image
src={nextGame[0].opponent.logo_url}
alt={`${nextGame[0].opponent.name} logo`}
width={100}
height={100}
className="self-center"
/>
{nextGame[0].opponent.name}
</Link>
</div>
</CardContent>
)}
</Card>
)
}
7 changes: 5 additions & 2 deletions src/server/functions/update-game-scores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import prisma from '../db/client'
import { scrapeGameScores } from '../scrapes/scrape-game-scores'

export const updateGameScores = async (): Promise<void> => {
const [scheduleInDb, gameScores] = await Promise.all([
const [scheduleInDb, gameScoresReg, gameScoresPlayoff] = await Promise.all([
prisma.game.findMany(),
scrapeGameScores(),
scrapeGameScores(false),
scrapeGameScores(true),
])

const gameScores = [...gameScoresReg, ...gameScoresPlayoff]

const gamesToUpdate = scheduleInDb.filter(game => {
const matchingGameScore = gameScores.find(gameScore =>
sameDay(game.date, gameScore.date)
Expand Down
36 changes: 20 additions & 16 deletions src/server/functions/update-game-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,31 +41,35 @@ export const updateGameStats = async (): Promise<void> => {
playerName
)

if (!player)
throw new Error(`Player ${playerName} not found in database`)
if (!player) return

const gameStatsInDb = await prisma.playerGame.findMany({
where: {
player_id: player.id,
},
})

const gamesWithIds = gameStats.map(gameStat => {
const dateISO = getDateOfGame(gameStat.date).toISOString()
const game = games.find(gme => sameDay(gme.date, dateISO))
const gamesWithIds = gameStats
.map(gameStat => {
const dateISO = getDateOfGame(gameStat.date).toISOString()
const game = games.find(gme => sameDay(gme.date, dateISO))

if (!game)
throw new Error(
`Game not found for date ${dateISO} ${player.first_name} ${player.last_name}`
)
const { date: _, ...rest } = gameStat
const { date: _, ...rest } = gameStat

return {
...rest,
game_id: game.id,
player_id: player.id,
}
})
if (!game)
return {
...rest,
game_id: '',
player_id: player.id,
}

return {
...rest,
game_id: game.id,
player_id: player.id,
}
})
.filter(gameStat => gameStat.game_id !== '')

const filteredGameStats = gamesWithIds.filter(
gameStat =>
Expand Down
1 change: 1 addition & 0 deletions src/server/functions/update-schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export const updateSchedule = async (): Promise<void> => {
home: game.home,
home_score: game.home_score,
opponent_score: game.opponent_score,
type: game.gameType,
},
})
})
Expand Down
1 change: 1 addition & 0 deletions src/server/routers/getRecord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const getRecord = publicProcedure
opponent_score: {
not: -1,
},
type: 'REGULAR',
},
})

Expand Down
6 changes: 4 additions & 2 deletions src/server/scrapes/scrape-game-scores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ interface IGameScoreScrape {
opponent_score: number
}

export const scrapeGameScores = async (): Promise<IGameScoreScrape[]> => {
export const scrapeGameScores = async (
playoffs: boolean
): Promise<IGameScoreScrape[]> => {
const res = await fetch(
`https://www.espn.co.uk/nba/team/schedule/_/name/den/season/${getCurrentSeason()}`
`https://www.espn.co.uk/nba/team/schedule/_/name/den/season/${getCurrentSeason()}/seasontype/${playoffs ? 3 : 2}`
)
const dom = new JSDOM(await res.text())
const rows = dom.window.document.querySelectorAll('.Table__TR')
Expand Down
15 changes: 14 additions & 1 deletion src/server/scrapes/scrape-schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface IScheduleScrape {
opponent_name: string
opponent_score: number
home_score: number
type: 'REGULAR' | 'PLAYOFF'
}

const convertTime12to24 = (time12h: string): string => {
Expand Down Expand Up @@ -44,9 +45,19 @@ export const scrapeSchedule = async (): Promise<IScheduleScrape[]> => {
`https://www.basketball-reference.com/teams/DEN/${getCurrentSeason()}_games.html`
)
const dom = new JSDOM(await res.text())
const rows = dom.window.document.getElementsByTagName('tr')
const regTable = dom.window.document.getElementById('games')
const playoffTable = dom.window.document.getElementById('games_playoffs')
const rows = Array.from(
(regTable as HTMLElement).getElementsByTagName('tr')
)

if (playoffTable) {
const playoffRows = playoffTable.getElementsByTagName('tr')
rows.push(...Array.from(playoffRows))
}

const schedule: IScheduleScrape[] = []
let gameCount = 0

for (let i = 0; i < rows.length; i++) {
const content = rows[i].children
Expand All @@ -58,6 +69,7 @@ export const scrapeSchedule = async (): Promise<IScheduleScrape[]> => {
content[0].textContent === 'G'
)
) {
gameCount++
// data that is the same for bothy completed and uncompleted games
const dateString = content[1].children[0].textContent as string
const rawTimeString = content[2].textContent as string
Expand Down Expand Up @@ -87,6 +99,7 @@ export const scrapeSchedule = async (): Promise<IScheduleScrape[]> => {
opponent_name: opponentName,
opponent_score: home ? opponentScore : teamScore,
home_score: home ? teamScore : opponentScore,
type: gameCount > 82 ? 'PLAYOFF' : 'REGULAR',
})
}
}
Expand Down

0 comments on commit 0b75bc1

Please sign in to comment.