## 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
93 lines
3.5 KiB
TypeScript
93 lines
3.5 KiB
TypeScript
import type { FetchedStandingsRecord, StandingsSyncAdapter } from "./types";
|
|
import {
|
|
flattenEspnStandings,
|
|
parseConferenceRank,
|
|
statsMap,
|
|
type EspnStandingsResponse,
|
|
} from "./espn";
|
|
|
|
const MLS_STANDINGS_URL =
|
|
"https://site.api.espn.com/apis/v2/sports/soccer/usa.1/standings";
|
|
|
|
/**
|
|
* Normalize ESPN conference group names to "Eastern" or "Western".
|
|
* ESPN returns names like "Eastern Conference" or "Western Conference".
|
|
*/
|
|
function normalizeConference(raw: string): string {
|
|
const upper = raw.toUpperCase();
|
|
if (upper === "EASTERN" || upper === "EASTERN CONFERENCE") return "Eastern";
|
|
if (upper === "WESTERN" || upper === "WESTERN CONFERENCE") return "Western";
|
|
return raw;
|
|
}
|
|
|
|
export class MlsStandingsAdapter implements StandingsSyncAdapter {
|
|
async fetchStandings(): Promise<FetchedStandingsRecord[]> {
|
|
const response = await fetch(MLS_STANDINGS_URL);
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
`MLS standings API returned ${response.status}: ${response.statusText}`
|
|
);
|
|
}
|
|
|
|
const json = (await response.json()) as EspnStandingsResponse;
|
|
const flattened = flattenEspnStandings(json);
|
|
|
|
if (flattened.length === 0) {
|
|
throw new Error(
|
|
"MLS standings API returned no entries — response shape may have changed"
|
|
);
|
|
}
|
|
|
|
// Pre-parse each entry's stats once, then sort by points desc for overall league rank.
|
|
const withSm = flattened.map(({ entry, conference }) => ({
|
|
entry,
|
|
conference,
|
|
sm: statsMap(entry.stats),
|
|
}));
|
|
|
|
const sorted = [...withSm].toSorted((a, b) => {
|
|
const ptsA = a.sm.get("points")?.value ?? 0;
|
|
const ptsB = b.sm.get("points")?.value ?? 0;
|
|
if (ptsB !== ptsA) return ptsB - ptsA;
|
|
const gdA = a.sm.get("pointDifferential")?.value ?? 0;
|
|
const gdB = b.sm.get("pointDifferential")?.value ?? 0;
|
|
return gdB - gdA;
|
|
});
|
|
|
|
return sorted.map(({ entry, conference, sm }, leagueIdx): FetchedStandingsRecord => {
|
|
const wins = sm.get("wins")?.value ?? 0;
|
|
const losses = sm.get("losses")?.value ?? 0;
|
|
const ties = sm.get("ties")?.value ?? sm.get("draws")?.value ?? 0;
|
|
const gamesPlayed = Math.round(
|
|
sm.get("gamesPlayed")?.value ?? wins + losses + ties
|
|
);
|
|
|
|
const tablePoints = sm.get("points")?.value;
|
|
const goalsFor = sm.get("pointsFor")?.value ?? sm.get("gf")?.value;
|
|
const goalsAgainst = sm.get("pointsAgainst")?.value ?? sm.get("ga")?.value;
|
|
const goalDifference = sm.get("pointDifferential")?.value ?? sm.get("gd")?.value;
|
|
|
|
const homeRecord = sm.get("Home")?.displayValue ?? undefined;
|
|
const awayRecord = sm.get("Road")?.displayValue ?? undefined;
|
|
|
|
return {
|
|
teamName: entry.team.displayName,
|
|
externalTeamId: entry.team.id,
|
|
wins: Math.round(wins),
|
|
losses: Math.round(losses),
|
|
ties: Math.round(ties),
|
|
tablePoints: tablePoints !== null && tablePoints !== undefined ? Math.round(tablePoints) : undefined,
|
|
goalsFor: goalsFor !== null && goalsFor !== undefined ? Math.round(goalsFor) : undefined,
|
|
goalsAgainst: goalsAgainst !== null && goalsAgainst !== undefined ? Math.round(goalsAgainst) : undefined,
|
|
goalDifference: goalDifference !== null && goalDifference !== undefined ? Math.round(goalDifference) : undefined,
|
|
winPct: gamesPlayed > 0 ? wins / gamesPlayed : 0,
|
|
gamesPlayed,
|
|
conference: normalizeConference(conference),
|
|
conferenceRank: parseConferenceRank(sm),
|
|
leagueRank: leagueIdx + 1,
|
|
homeRecord,
|
|
awayRecord,
|
|
};
|
|
});
|
|
}
|
|
}
|