# Currency Converter API

REST API that serves currency exchange rates and converts between currencies. Rates are fetched from [ExchangeRate-API](https://www.exchangerate-api.com/) and refreshed automatically once a week via a cron job, so requests are always served from the database (no live upstream call per request).

## Setup

1. Copy `.env.example` to `.env` and fill in:
   - `EXCHANGE_RATE_API_KEY` — your key from https://www.exchangerate-api.com/
   - `DATABASE_URL` — Postgres connection string
2. Install dependencies:
   ```bash
   npm install
   ```
3. Start the server:
   ```bash
   npm start
   ```
   On first boot it creates the `exchange_rates` table and seeds it with a live fetch if empty.

## How the weekly update works

`src/cron/rateUpdateJob.js` schedules a [node-cron](https://www.npmjs.com/package/node-cron) job (`0 0 * * 1` — every Monday at midnight) that calls the same fetch-and-store logic used at boot, upserting one row per (date, base currency) into Postgres.

To trigger a refresh manually (e.g. from your own external cron/scheduler instead of the in-process one):
```bash
npm run sync-rates
```
or `POST /api/rates/refresh`.

## Endpoints

| Method | Path | Description |
|---|---|---|
| GET | `/api/rates/latest?base=USD` | Latest stored rates for a base currency (defaults to `EXCHANGE_RATE_BASE_CURRENCY`) |
| GET | `/api/rates/:date?base=USD` | Stored rates for a specific date (`YYYY-MM-DD`) |
| GET | `/api/convert?from=USD&to=INR&amount=100` | Convert an amount using the latest stored rates |
| POST | `/api/rates/refresh` | Force an immediate fetch + store from ExchangeRate-API |
| GET | `/health` | Health check |

## Data model

Table `exchange_rates`: `date`, `base`, `rates` (JSONB map of lowercase currency code → rate relative to `base`), unique on `(date, base)` — matching the shape in the prompt, but generated per API response rather than hand-authored crypto/fiat lists (ExchangeRate-API's free/basic plans return fiat only).
