# Sync to your own database incrementally

Source: https://developers.newjune.co/guides/incremental-sync

> Keep a copy of your rounds, hole scores, and shots up to date with updated_after and a stored watermark.

A sync job keeps a copy of your rounds, hole scores, and shots in your own store and refreshes it on a schedule. Each run asks only for what changed since the last one. The pattern:

1. **Keep one watermark per resource:** the newest `updated_at` you have stored for rounds, for hole scores, and for shots. Before the first run there is none.
2. **Each run, for each resource:** list with `updated_after` set to the watermark minus a five-minute overlap (or `1970-01-01T00:00:00Z` on the first run), walk every page, and upsert each item by `id`.
3. **Move the watermark** to the newest `updated_at` you saw, and only after every page came back. If a run fails halfway, the next run starts from the old watermark and picks up the rest.

## The filters this uses

| Need | Request | Notes |
| --- | --- | --- |
| Rounds that changed | `GET /v1/rounds?updated_after=...` | Compares the round's own `updated_at`, strictly after the value. |
| Hole scores that changed, across every round | `GET /v1/hole_scores?updated_after=...` | Hole scores need `round_id`, `updated_after`, or both. |
| Shots that changed | `GET /v1/shots?updated_after=...` | Also works together with `round_id`. |

`updated_after` takes an ISO 8601 time with `Z` or an offset and keeps items whose own `updated_at` is strictly later. It does not change the list order or how cursors work, so walk every page before you move the watermark. The same filter works on `priorities`, `plans`, and `clubs`.

Each resource has its own watermark because each `updated_at` moves on its own:

- **A round's `updated_at` does not move when its hole scores change.** Entering or editing a score changes the round's `holes_scored`, `total_strokes`, `par_total`, and `score_to_par`, but not its `updated_at`. Sync hole scores with their own `updated_after`, and recompute those totals from your stored hole scores, or re-read the round when one of its hole scores changes.
- **A hole score's `updated_at` does not move when par or yardage change.** Those come from the round's scorecard or the course.
- **A plan's `updated_at` does not move when a step is marked done or open.** If you sync plans, compare their steps.

**Needs:** a key with `rounds:read`, exported as `NEW_JUNE_API_KEY`.

curl:

```bash
#!/usr/bin/env bash
# sync.sh: needs curl and jq. Stores one JSON file per item under ./newjune/.
set -euo pipefail

dir="newjune"
auth="Authorization: Bearer $NEW_JUNE_API_KEY"
overlap=300 # seconds of overlap; items seen twice are upserted twice, which is harmless

fetch_all() {
  local base="$1" cursor="" page
  while :; do
    local url="$base"
    if [ -n "$cursor" ]; then url="$url&cursor=$cursor"; fi
    page=$(curl -sf "$url" -H "$auth")
    echo "$page" | jq -c '.data[]'
    if [ "$(echo "$page" | jq -r '.has_more')" != "true" ]; then break; fi
    cursor=$(echo "$page" | jq -r '.next_cursor')
  done
}

# sync_resource <name> <list URL ending in updated_after=>
sync_resource() {
  local name="$1" base="$2" mark="$dir/$1.watermark" since="1970-01-01T00:00:00Z" newest=""
  mkdir -p "$dir/$name"
  if [ -f "$mark" ]; then
    newest=$(cat "$mark")
    since=$(jq -rn --arg t "$newest" --argjson o "$overlap" \
      '($t | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601) - $o | todateiso8601')
  fi
  # Fetch every page first: if a request fails, the script stops before
  # anything is stored and the watermark stays where it was.
  local items count=0
  items=$(mktemp)
  fetch_all "$base$since" > "$items"
  while read -r item; do
    echo "$item" > "$dir/$name/$(echo "$item" | jq -r '.id').json" # upsert by id
    updated=$(echo "$item" | jq -r '.updated_at')
    if [[ "$updated" > "$newest" ]]; then newest="$updated"; fi
    count=$((count + 1))
  done < "$items"
  rm -f "$items"
  if [ -n "$newest" ]; then echo "$newest" > "$mark"; fi
  echo "$name: $count new or changed"
}

sync_resource rounds "https://data.newjune.co/v1/rounds?limit=100&updated_after="
sync_resource hole_scores "https://data.newjune.co/v1/hole_scores?limit=100&updated_after="
sync_resource shots "https://data.newjune.co/v1/shots?limit=100&updated_after="
```

TypeScript:

```ts
// sync.mts: Node 20+, no dependencies. Run with: npx tsx sync.mts
// Stores everything in newjune.json; replace load/save with your database.
import { existsSync, readFileSync, writeFileSync } from 'node:fs';

type Resource = 'rounds' | 'hole_scores' | 'shots';
interface Item { id: string; updated_at: string }
interface Store {
  watermarks: Partial<Record<Resource, string>>;
  items: Record<Resource, Record<string, Item>>;
}

const STORE_FILE = 'newjune.json';
// Overlap: items seen twice are upserted twice, which is harmless.
const OVERLAP_MS = 5 * 60 * 1000;

async function* listAll<T>(path: string, params: Record<string, string> = {}) {
  let cursor: string | null = null;
  do {
    const url = new URL(`https://data.newjune.co/v1/${path}`);
    url.searchParams.set('limit', '100');
    for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
    if (cursor) url.searchParams.set('cursor', cursor);
    const response = await fetch(url, {
      headers: { Authorization: `Bearer ${process.env.NEW_JUNE_API_KEY}` },
    });
    if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
    const page = (await response.json()) as { data: T[]; has_more: boolean; next_cursor: string | null };
    yield* page.data;
    cursor = page.has_more ? page.next_cursor : null;
  } while (cursor);
}

const store: Store = existsSync(STORE_FILE)
  ? JSON.parse(readFileSync(STORE_FILE, 'utf8'))
  : { watermarks: {}, items: { rounds: {}, hole_scores: {}, shots: {} } };

function since(resource: Resource): string {
  const watermark = store.watermarks[resource];
  return watermark
    ? new Date(Date.parse(watermark) - OVERLAP_MS).toISOString()
    : '1970-01-01T00:00:00Z';
}

async function sync(resource: Resource, items: AsyncIterable<Item>): Promise<void> {
  let newest = store.watermarks[resource];
  let count = 0;
  for await (const item of items) {
    store.items[resource][item.id] = item; // upsert by id
    if (!newest || item.updated_at > newest) newest = item.updated_at;
    count += 1;
  }
  if (newest) store.watermarks[resource] = newest;
  console.log(`${resource}: ${count} new or changed`);
}

await sync('rounds', listAll<Item>('rounds', { updated_after: since('rounds') }));
await sync('hole_scores', listAll<Item>('hole_scores', { updated_after: since('hole_scores') }));
await sync('shots', listAll<Item>('shots', { updated_after: since('shots') }));

// Saved only when every page of every resource came back, so a failed run
// leaves the old watermarks and the next run picks up the rest.
writeFileSync(STORE_FILE, JSON.stringify(store));
```

Python:

```python
# sync.py: needs requests (pip install requests). Uses SQLite from the standard library.
import json
import os
import sqlite3
from datetime import datetime, timedelta
import requests

API = "https://data.newjune.co/v1"
OVERLAP = timedelta(minutes=5)  # items seen twice are upserted twice, which is harmless
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['NEW_JUNE_API_KEY']}"

def list_all(path, **params):
    params = {"limit": 100, **params}
    while True:
        response = session.get(f"{API}/{path}", params=params, timeout=30)
        response.raise_for_status()
        page = response.json()
        yield from page["data"]
        if not page["has_more"]:
            return
        params["cursor"] = page["next_cursor"]

db = sqlite3.connect("newjune.db")
db.executescript("""
    create table if not exists watermarks (resource text primary key, updated_at text);
    create table if not exists rounds (id text primary key, updated_at text, body text);
    create table if not exists hole_scores (id text primary key, updated_at text, body text);
    create table if not exists shots (id text primary key, updated_at text, body text);
""")

def since(resource):
    row = db.execute("select updated_at from watermarks where resource = ?", (resource,)).fetchone()
    if row is None:
        return "1970-01-01T00:00:00Z"
    start = datetime.fromisoformat(row[0].replace("Z", "+00:00")) - OVERLAP
    return start.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

def sync(resource, items):
    newest, count = None, 0
    # One transaction per resource: if any page fails, nothing is stored
    # and the watermark stays where it was.
    with db:
        for item in items:
            db.execute(
                f"insert into {resource} values (?, ?, ?) on conflict(id) do update set "
                "updated_at = excluded.updated_at, body = excluded.body",
                (item["id"], item["updated_at"], json.dumps(item)),
            )
            newest = max(newest or item["updated_at"], item["updated_at"])
            count += 1
        if newest:
            db.execute(
                "insert into watermarks values (?, ?) on conflict(resource) do update set "
                "updated_at = max(watermarks.updated_at, excluded.updated_at)",
                (resource, newest),
            )
    print(f"{resource}: {count} new or changed")

sync("rounds", list_all("rounds", updated_after=since("rounds")))
sync("hole_scores", list_all("hole_scores", updated_after=since("hole_scores")))
sync("shots", list_all("shots", updated_after=since("shots")))
```

## Why the overlap

Each run asks for items changed after the watermark minus five minutes, not after the watermark itself:

- A change saved in a database transaction that started earlier can carry an `updated_at` slightly older than one you already stored. Without an overlap, a run that happens at that moment would skip it.
- `updated_at` is published to the millisecond. Asking for exactly the stored value can return that same item again.

Both only mean that some items come back twice. Upserting by `id` makes a repeat harmless, so err on the side of a wider overlap, not a narrower one.

## Run it on a schedule

Run the script from cron, a CI schedule, or a serverless cron job. Every 15 minutes to every hour is plenty: rounds change while you play and shortly after.

```bash
# crontab: every 30 minutes. secrets.env holds: export NEW_JUNE_API_KEY=...
*/30 * * * * cd /path/to/sync && . ./secrets.env && python3 sync.py >> sync.log 2>&1
```

Keep `secrets.env` readable only by the job's user (`chmod 600`), or use your scheduler's secret store.

## Notes

- **Cost per run:** one request per page of changed items for each resource. When nothing changed, a run is three requests. The first run lists everything once.
- **Deletions:** the API has no deleted-object feed, and a deleted item simply stops appearing, so `updated_after` never reports it. Once a week, list every round without filters, then each round's `GET /v1/hole_scores?round_id=...` and `GET /v1/shots?round_id=...`, and delete stored items that did not come back.
- **Test rounds** are never returned, so they never reach your store.
- **Priorities, plans, and clubs** take `updated_after` too: add them with the same function and their own watermarks (scopes `plans:read` and `clubs:read`).
- **Reports, evaluations, and focus sets** have no `updated_at`. Reports and evaluations are listed newest first (`created_at` and `evaluated_at`), so read pages until you reach ones you already have. Focus sets are few; list them all on each run, since `effective_until` is set when a set is replaced.
