npm package: @sportsdatabase/sdk
Description: Official TypeScript SDK for SportsDatabase.io
Author: SportsDatabase.io
Latest version: 0.0.2

# SportsDatabase TypeScript SDK

Official TypeScript client for SportsDatabase.io, providing typed access to leagues, teams, events, schedules, scores, and more with first-class pagination helpers and error handling.

## Installation

```bash
npm install @sportsdatabase/sdk
# or
yarn add @sportsdatabase/sdk
```

## Quick Start

```ts
import { SportsDatabaseClient } from '@sportsdatabase/sdk';

const client = new SportsDatabaseClient({
  apiKey: process.env.SPORTSDB_API_KEY!,
  baseUrl: 'https://api.sportsdatabase.io/v1'
});

const games = await client.events.getByDate({ sport: 'soccer', date: '2025-05-01' });
console.log(games.data.map((event) => `${event.homeTeamId} vs ${event.awayTeamId}`));
```

## ELI5: Getting Started Fast

1. **Install the package** – run `npm install @sportsdatabase/sdk`.
2. **Grab your API key** – copy it from the SportsDatabase portal.
3. **Create the client** – drop this snippet into your app:
   ```ts
   import { SportsDatabaseClient } from '@sportsdatabase/sdk';

    const client = new SportsDatabaseClient({ apiKey: 'YOUR_KEY' });
   ```
4. **Make a call** – try `client.leagues.list({ sportSlug: 'soccer' })` and log the `data`.
5. **Handle pagination** – if `meta.nextCursor` exists, pass it back in `cursor` to fetch the next page (or use `client.events.iterate` to do it for you).
6. **Watch rate limits** – every response includes `meta.rateLimit` and `meta.requestId`, so log them when debugging.
7. **Avoid surprises** – wrap calls in `try/catch` and check for `ApiError`, `RateLimitError`, or `NetworkError` to show friendly messages.

If you can run `node sample.js` and see JSON printed, you’re good to explore deeper endpoints.

## Configuration

| Option            | Type     | Default                           | Description                                        |
|-------------------|----------|-----------------------------------|----------------------------------------------------|
| `apiKey`          | string   | required                          | API key from the SportsDatabase portal             |
| `baseUrl`         | string   | `https://api.sportsdatabase.io/v1`| Override for staging/self-hosted deployments       |
| `timeoutMs`       | number   | `10_000`                          | Request timeout in milliseconds                    |
| `maxRetries`      | number   | `2`                               | Automatic retries for 429/5xx responses            |
| `userAgentSuffix` | string   | `''`                              | Extra identifier appended to SDK user-agent        |

## Endpoints Overview

- `client.sports` *(coming soon)* — list available sports.
- `client.leagues.list({ sportSlug, status })`
- `client.teams.list({ leagueId, season })`
- `client.events.list({ sport, league, date, status })`
- `client.events.iterate(...)` — async iterator over paginated events.
- `client.schedules.teamNext({ teamId })`, `client.schedules.iterateLeagueSeason(...)`
- `client.scores.getByEvent(eventId)` — latest score snapshot.

Each method returns a typed response with `data` and `meta` (including rate-limit headers and request ID).

## Pagination Helpers

Use `client.events.iterate()` or the exported helpers:

```ts
import { iterateItems } from '@sportsdatabase/sdk';

const iterator = iterateItems(client.events.list.bind(client.events), {
  initialParams: { sport: 'basketball', limit: 50 }
});

for await (const event of iterator) {
  // consume pages transparently
}
```

## Error Handling

Errors extend `SportsDatabaseError` and include:

- `ApiError` — non-2xx responses with `status`, `code`, `details`.
- `RateLimitError` — 429 responses with `resetAt`.
- `NetworkError` — network failures after retry attempts.

```ts
try {
  await client.events.getById('evt_123');
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Retry after ${error.resetAt}`);
  }
}
```

## Examples

| Script                   | Description                         |
|--------------------------|-------------------------------------|
| `examples/get_today_events.ts` | Fetches today's soccer events |
| `examples/list_leagues.ts`     | Lists active leagues for a sport |
| `examples/smoke_test.ts`       | Integration smoke script       |

Run via `tsx`/`ts-node` or compile with `tsc`.

## Development

```bash
npm install
npm run lint
npm run test
```

CI runs linting, type-checking, and tests via GitHub Actions (`.github/workflows/ci.yml`).

## Versioning

This SDK follows semantic versioning and mirrors major/minor releases of the public API:

- `MAJOR` version only changes when the API introduces breaking changes that require SDK adjustments.
- `MINOR` bumps ship new endpoints or fields that are backward-compatible.
- `PATCH` releases contain bug fixes or documentation updates.

Publish from a clean tree after running `npm run lint`, `npm run test`, and `npm run build`, then `npm publish --access public`.

## License

MIT © SportsDatabase.io