brackt/app/services/standings-sync/wnba.ts
chrisp add196902b
All checks were successful
🚀 Deploy / 🧪 Test (push) Successful in 2m21s
🚀 Deploy / ʦ TypeScript (push) Successful in 1m18s
🚀 Deploy / 🔍 Lint (push) Successful in 49s
🚀 Deploy / 🐳 Build (push) Successful in 12m18s
🚀 Deploy / 🚀 Deploy (push) Successful in 12s
Fix MLB standings 406 error and refactor ESPN adapter shared code (#62)
## Summary

- **Root cause**: `statsapi.mlb.com` returns 406 (deprecated). Switched MLB to ESPN's free standings API (`site.api.espn.com/apis/v2/sports/baseball/mlb/standings`), consistent with NBA, WNBA, and MLS.
- **Refactor**: Extracted a shared `espn.ts` utility module, eliminating 4× duplication of `statsMap()`, `flattenEspnStandings()`, ESPN interfaces, and the `playoffSeed` → conference rank logic across adapters.
- **Bug fixes** found during review and applied across all affected adapters:
  - `parseConferenceRank`: `|| undefined` falsy-zero bug replaced with `isNaN` guard
  - Sort comparators: stable alphabetical tiebreaker added to MLB, NBA, WNBA
  - `winPct`: falls back to `wins/(wins+losses)` if ESPN omits the stat (was silently 0)
  - statsMap pre-built once per entry before sorting in all adapters (was rebuilt per comparison)
  - WNBA `parseEntry`: accepts pre-computed `sm` instead of rebuilding it internally
  - MLB `gamesBack`: tests updated to reflect ESPN returns numeric `0` for division leaders (old API used `"-"` → `undefined`)

## Test plan

- [ ] All 60 standings-sync unit tests pass (`npm run test:run -- app/services/standings-sync`)
- [ ] Trigger MLB standings sync from admin panel and confirm it returns data without a 406
- [ ] Confirm NBA, WNBA, MLS syncs still work (adapters touched but behaviour unchanged)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #62
2026-06-01 03:31:18 +00: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;
}
}