brackt/app/services/standings-sync/wnba.ts
Chris Parsons e353c17a0b
Some checks failed
🚀 Deploy / 🧪 Test (pull_request) Successful in 2m28s
🚀 Deploy / ʦ TypeScript (pull_request) Failing after 1m9s
🚀 Deploy / 🔍 Lint (pull_request) Successful in 46s
🚀 Deploy / 🐳 Build (pull_request) Has been skipped
🚀 Deploy / 🚀 Deploy (pull_request) Has been skipped
Fix MLB standings 406 error and refactor ESPN adapter shared code
- Switch MLB standings from deprecated statsapi.mlb.com to ESPN API
  (same source as NBA, WNBA, MLS — no auth required)
- Extract shared espn.ts utility: EspnStat/Team/Entry/Group/Response
  interfaces, statsMap(), flattenEspnStandings(), parseConferenceRank(),
  sortByWinLoss(); removes 4× duplication across adapters
- Fix parseConferenceRank falsy-zero bug (|| undefined → isNaN guard)
- Add stable alphabetical tiebreaker to MLB, NBA, WNBA sort comparators
- Fix winPct silent-zero: fall back to wins/(wins+losses) if ESPN omits stat
- Pre-build statsMap once per entry before sorting in all adapters
- Fix WNBA parseEntry to accept pre-computed sm instead of rebuilding it
- Restore and update gamesBack tests (ESPN returns numeric 0 for leaders,
  not the old API's "-" string)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 18:18:15 -07:00

221 lines
7 KiB
TypeScript

import type { FetchedStandingsRecord, StandingsSyncAdapter } from "./types";
import {
parseConferenceRank,
sortByWinLoss,
statsMap,
type EspnStat,
type EspnStandingsEntry,
type EspnStandingsResponse,
} from "./espn";
const WNBA_STANDINGS_URL =
"https://site.api.espn.com/apis/v2/sports/basketball/wnba/standings";
/**
* Returns all registered WNBA teams (including pre-season expansion teams not yet
* in standings). Used to supplement the standings response so every team gets a record.
*/
const WNBA_TEAMS_URL =
"https://site.api.espn.com/apis/site/v2/sports/basketball/wnba/teams";
interface EspnTeamItem {
team: {
id: string;
displayName: string;
isActive?: boolean;
};
}
interface EspnTeamsResponse {
sports?: Array<{
leagues?: Array<{
teams?: EspnTeamItem[];
}>;
}>;
}
/**
* WNBA-specific flatten: conferences may be directly under root or wrapped in a
* single top-level group. ESPN sometimes wraps them; handle both layouts.
*/
function flattenWnbaStandings(
response: EspnStandingsResponse
): Array<{ entry: EspnStandingsEntry; conference: string }> {
const results: Array<{ entry: EspnStandingsEntry; conference: string }> = [];
for (const topGroup of response.children ?? []) {
if (topGroup.children && topGroup.children.length > 0) {
// Top-level group has sub-groups — each sub-group is a conference (no divisions).
for (const confGroup of topGroup.children) {
const conferenceName = confGroup.name ?? topGroup.name ?? "";
for (const entry of confGroup.standings?.entries ?? []) {
results.push({ entry, conference: conferenceName });
}
}
} else {
// Top-level group is the conference itself.
const conferenceName = topGroup.name ?? "";
for (const entry of topGroup.standings?.entries ?? []) {
results.push({ entry, conference: conferenceName });
}
}
}
return results;
}
/** Parse a standings entry into a FetchedStandingsRecord (rank assigned by caller). */
function parseEntry(
entry: EspnStandingsEntry,
sm: Map<string, EspnStat>,
conference: string,
leagueRank: number
): FetchedStandingsRecord {
const wins = sm.get("wins")?.value ?? 0;
const losses = sm.get("losses")?.value ?? 0;
// Fall back to computing win% from wins/losses if ESPN omits the stat.
const winPctStat = sm.get("winPercent")?.value ?? sm.get("winPct")?.value;
const winPct = winPctStat ?? (wins + losses > 0 ? wins / (wins + losses) : 0);
const gamesBehind = sm.get("gamesBehind")?.value;
const streak =
sm.get("streak")?.displayValue ??
sm.get("streakSummary")?.displayValue;
const lastTen =
sm.get("Last Ten Games")?.displayValue ??
sm.get("L10")?.displayValue ??
undefined;
const homeRecord = sm.get("Home")?.displayValue ?? undefined;
const awayRecord = sm.get("Road")?.displayValue ?? undefined;
// SRS proxy: average point differential per game.
// ESPN exposes "avgPointsFor" and "avgPointsAgainst" (or "pointsFor"/"pointsAgainst").
// If unavailable, fall back to null so the simulator uses the league-average Elo (1500).
const ptFor =
sm.get("avgPointsFor")?.value ??
sm.get("pointsFor")?.value ??
null;
const ptAgainst =
sm.get("avgPointsAgainst")?.value ??
sm.get("pointsAgainst")?.value ??
null;
const srs =
ptFor !== null && ptFor !== undefined &&
ptAgainst !== null && ptAgainst !== undefined
? Math.round((ptFor - ptAgainst) * 100) / 100
: null;
return {
teamName: entry.team.displayName,
externalTeamId: entry.team.id,
wins: Math.round(wins),
losses: Math.round(losses),
winPct,
gamesPlayed: Math.round(wins) + Math.round(losses),
gamesBack: gamesBehind,
conference: conference || undefined,
conferenceRank: parseConferenceRank(sm),
leagueRank,
streak,
lastTen,
homeRecord,
awayRecord,
srs,
};
}
export class WnbaStandingsAdapter implements StandingsSyncAdapter {
async fetchStandings(): Promise<FetchedStandingsRecord[]> {
// Fetch both endpoints in parallel.
const [standingsResponse, teamsResponse] = await Promise.all([
fetch(WNBA_STANDINGS_URL),
fetch(WNBA_TEAMS_URL),
]);
if (!standingsResponse.ok) {
throw new Error(
`WNBA standings API returned ${standingsResponse.status}: ${standingsResponse.statusText}`
);
}
if (!teamsResponse.ok) {
throw new Error(
`WNBA teams API returned ${teamsResponse.status}: ${teamsResponse.statusText}`
);
}
const [standingsJson, teamsJson] = await Promise.all([
standingsResponse.json() as Promise<EspnStandingsResponse>,
teamsResponse.json() as Promise<EspnTeamsResponse>,
]);
// Build standings records from the standings endpoint, sorted by wins desc.
// Pre-parse each entry once so statsMap isn't rebuilt multiple times per entry.
const flattened = flattenWnbaStandings(standingsJson).map(({ entry, conference }) => ({
entry,
conference,
sm: statsMap(entry.stats),
}));
const sortedEntries = [...flattened].toSorted(sortByWinLoss);
// Map externalTeamId → parsed record (so we can detect which teams are missing).
const recordsByTeamId = new Map<string, FetchedStandingsRecord>();
sortedEntries.forEach(({ entry, sm, conference }, idx) => {
recordsByTeamId.set(
entry.team.id,
parseEntry(entry, sm, conference, idx + 1)
);
});
// Extract the full team list from the teams endpoint.
const allTeams: Array<{ id: string; displayName: string }> = (
teamsJson.sports?.[0]?.leagues?.[0]?.teams ?? []
)
.filter((t) => t.team.isActive !== false)
.map((t) => ({ id: t.team.id, displayName: t.team.displayName }));
if (allTeams.length === 0 && recordsByTeamId.size === 0) {
throw new Error(
"WNBA standings API returned no entries — response shape may have changed"
);
}
// Merge: use standing records where available; fill in zero-records for
// expansion teams not yet in the standings (pre-season or mid-season addition).
const results: FetchedStandingsRecord[] = [];
const seenIds = new Set<string>();
// First, add all teams that have standings data (preserving their rank).
for (const record of recordsByTeamId.values()) {
results.push(record);
seenIds.add(record.externalTeamId);
}
// Then, append zero-records for any team in the teams list but not in standings.
let expansionRank = results.length + 1;
for (const team of allTeams) {
if (!seenIds.has(team.id)) {
results.push({
teamName: team.displayName,
externalTeamId: team.id,
wins: 0,
losses: 0,
winPct: 0,
gamesPlayed: 0,
leagueRank: expansionRank++,
srs: null,
});
}
}
// If the teams endpoint returned nothing (API change), fall back to standings only.
if (results.length === 0) {
throw new Error(
"WNBA standings API returned no entries — response shape may have changed"
);
}
return results;
}
}