> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Data fetching

All server data flows through [`@tanstack/react-query`](https://tanstack.com/query). A single `QueryClient` is created in [src/core/services/queryClient.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/queryClient.ts) and provided by `AppProviders`. Components never call `api.ts` directly; they always go through `queries.ts`. The `tracks` names in the snippets below are illustrative — the tracks feature no longer ships these files.

## Layer pipeline

```mermaid
flowchart LR
  comp[Screen / component] --> hook["queries.ts hook<br/>(useTracksQuery)"]
  hook --> mapper["mappers.ts<br/>toTrack(dto)"]
  hook --> apiFn["api.ts<br/>fetchTracks()"]
  apiFn --> client["core/services/apiClient.ts<br/>fetch wrapper"]
  client --> wire[(Network)]
  wire --> client
  client --> apiFn
  apiFn --> mapper
  mapper --> hook
  hook --> cache[(React Query cache)]
  cache --> comp
```

## Catalog — bundled from Google Sheet (build time)

The song catalog in [`src/features/catalog/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/catalog/) is **not** fetched at runtime. A build-time script downloads the published Google Sheet CSV (see [`src/core/config/song-config.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/config/song-config.ts)), maps rows in `sheet-mappers.ts`, downloads MIDI / section MIDI / BGM / preview bytes, converts MIDI to offline chart JSON in memory, and writes bundled artifacts under `src/assets/`:

- [`src/assets/config/songs.json`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/config/songs.json) — catalog metadata (no remote MIDI/BGM URLs)
- [`src/assets/charts/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/charts/) — offline `ChartJson` (MIDI→JSON at sync; raw `.mid` is not stored)
- [`src/assets/audio/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/audio/) — pre-mastered backing tracks
- [`src/assets/previews/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/previews/) — song-list preview clips
- Generated Metro maps: [`src/core/sdk/song-assets.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/song-assets.ts), [`src/assets/charts/manifest.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/charts/manifest.ts), and [`src/assets/previews/index.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/previews/index.ts) — all gitignored, materialized by `catalog:sync-sheet` / `ensure-catalog-generated.ts`

Run manually after sheet edits:

```bash
bun run catalog:sync-sheet
```

The same script also runs on `postinstall` (always re-downloads sheet assets). Offline installs reuse the previously-bundled files on disk when the CSV fetch fails.

At runtime, `useCatalogSongsQuery` reads bundled `songs.json` with `staleTime: Infinity` (no network refetch). Delisted owned songs are still merged from [`@piano/user-library`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/user-library/). Legacy MMKV catalog cache (`cache.ts`) and `catalog-media-sync.ts` remain for owned-song remote snapshots but are not driven by sheet refresh anymore.

```mermaid
flowchart LR
  sheet[(Google Sheet CSV)] --> sync["scripts/sync-catalog-from-sheet.ts"]
  sync --> bundled["src/assets/config + midi + audio + previews"]
  bundled --> query["useCatalogSongsQuery"]
  query --> merge["catalog-merge.ts<br/>+ user-library delisted"]
  merge --> screen[SongsScreen]
  bundled --> hybrid["HybridMidiRepository<br/>bundled-first"]
  hybrid --> play[Play / prepare screen]
```

See [features/catalog.md](/docs/features/catalog.md) for the full catalog contract.

## QueryClient defaults

```ts
// src/core/services/queryClient.ts
export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,
      retry: 1,
      refetchOnWindowFocus: false,
    },
    mutations: { retry: 0 },
  },
});
```

- `staleTime: 30_000` — 30s grace before data is considered stale; reduces refetch storms while still feeling fresh.
- `retry: 1` — one silent retry; UI shows error on second failure.
- `refetchOnWindowFocus: false` — React Native lacks a true "focus" event the way browsers do; the default is noisy. Pair with `AppState` listeners if needed later.

## The api client (axios)

[`src/core/services/apiClient.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/apiClient.ts) exports a single, configured `axios` instance plus a `configureApiClient(hooks)` setter so the composition root can wire in auth and 401 handling without `core/services/` ever importing from `features/`.

```ts
// src/core/services/apiClient.ts (summary)
export const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10_000,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});
```

Usage in `api.ts`:

```ts
import { apiClient } from '@services/apiClient';
import type { TrackDto } from './types';

export const fetchTracks = async (search?: string) => {
  const { data } = await apiClient.get<TrackDto[]>('/tracks', { params: { q: search } });
  return data;
};

export const postSession = async (payload: SignInPayload) => {
  const { data } = await apiClient.post<SessionDto>('/sessions', payload);
  return data;
};
```

> Existing feature `api.ts` files still use in-memory mocks for the demo. Swap them to `apiClient` calls when a backend exists.

## Interceptors

Two interceptors are attached automatically:

```mermaid
flowchart LR
  caller["api.ts call"] --> req[request interceptor]
  req -->|"add Bearer token<br/>if getAuthToken returns one"| http[(HTTP)]
  http --> res[response interceptor]
  res -->|"2xx"| caller
  res -->|"4xx / 5xx"| handler{status?}
  handler -->|"401"| onUnauth[onUnauthorized hook]
  handler -->|"403"| onForb[onForbidden hook]
  handler -->|"other"| reject
  onUnauth --> reject[Promise.reject with ApiError]
  onForb --> reject
  reject --> caller
```

### Request interceptor — attach auth token

Pulls the token from whatever the composition root registered. If no token, the request goes out unauthenticated.

### Response interceptor — handle errors

- Wraps any error in a typed `ApiError(status, message, data)` so feature code only catches one error class.
- On `401 Unauthorized`, calls the registered `onUnauthorized` hook (sign out + redirect — see below).
- On `403 Forbidden`, calls `onForbidden` (currently a no-op, reserved for future "you don't have permission" UX).

## 401 — global sign-out flow

The 401 handler only mutates state; **the root `app/_layout.tsx`'s `<Stack.Protected>` blocks then reactively swap to `(auth)`** because `session` became `null`. No imperative `router.replace` is needed (and adding one would race with the root layout's own re-render).

```mermaid
sequenceDiagram
  participant Code as Any api.ts call
  participant Axios as apiClient
  participant API as Backend
  participant Hook as onUnauthorized
  participant SignOut as performSignOut()
  participant Stores as auth · tracks · pianoUi
  participant QC as queryClient
  participant Layout as app/_layout (ProtectedRoutes)
  participant Router as expo-router

  Code->>Axios: GET /something
  Axios->>API: with stale Bearer
  API-->>Axios: 401 Unauthorized
  Axios->>Hook: call hook
  Hook->>SignOut: performSignOut()
  SignOut->>Stores: signOut() + reset()
  Stores-->>Stores: clear session in MMKV "auth"
  SignOut->>QC: queryClient.clear()
  Stores-->>Layout: zustand notifies subscribers
  Layout-->>Router: re-render Stack, (auth) guard now wins
  Axios-->>Code: reject ApiError(401, ...)
```

### Registration

[`src/core/entrySetup.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/entrySetup.ts) is the composition root. It runs once at app boot — `app/_layout.tsx` imports it as a side effect at the very top of the file, so axios hooks are wired before any React component mounts (and therefore before the first `queries.ts` hook can fire):

```ts
// app/_layout.tsx
import '@/core/entrySetup'; // ← top of file, side-effect import
```

```ts
// src/core/entrySetup.ts
import 'react-native-gesture-handler';

import { performSignOut } from '@/features/auth/signOut';
import { useAuthStore } from '@/features/auth/store';
import { configureApiClient } from './services/apiClient';

configureApiClient({
  getAuthToken: () => useAuthStore.getState().session?.accessToken ?? null,
  onUnauthorized: () => {
    if (!useAuthStore.getState().session) return; // already signed out
    performSignOut();
    // No router.replace here — the root layout's <Stack.Protected> blocks
    // react to session=null and swap to the (auth) stack automatically.
  },
});
```

The "already signed out" guard prevents repeated state churn if multiple stale 401s arrive in flight. `performSignOut()` (in [src/features/auth/signOut.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/auth/signOut.ts)) is the single canonical exit path — it clears the auth store, resets `tracks` + `pianoUi` stores, and `queryClient.clear()`s the cache in one call. Use it from manual sign-out buttons too, never inline the steps.

## Catching ApiError in code

```ts
import axios from 'axios';
import { ApiError } from '@services/apiClient';

try {
  await fetchTracks();
} catch (err) {
  if (err instanceof ApiError && err.status === 404) {
    // soft empty state
  } else {
    throw err;
  }
}
```

Inside `useMutation` / `useQuery`, errors are already `ApiError` instances thanks to the response interceptor, so `error.status` is always defined.

## Query key conventions

Every feature exports a `keys` object so cache invalidation never relies on string literals.

```ts
// e.g. src/features/<feature>/queries.ts
export const tracksKeys = {
  all: ['tracks'] as const,
  list: (search: string) => [...tracksKeys.all, 'list', { search }] as const,
  detail: (id: string) => [...tracksKeys.all, 'detail', id] as const,
};
```

Mutations invalidate using the hierarchy:

```ts
queryClient.invalidateQueries({ queryKey: tracksKeys.all });          // both lists + details
queryClient.invalidateQueries({ queryKey: tracksKeys.detail(id) });   // just one detail
```

## Optimistic update — toggle favorite

```mermaid
sequenceDiagram
  participant U as User
  participant V as TrackDetailScreen
  participant M as useToggleFavoriteMutation
  participant C as queryClient cache
  participant API as api.toggleFavoriteRequest

  U->>V: Tap "Favorite"
  V->>M: mutate(id)
  M->>C: onMutate -> cancel + snapshot
  M->>C: setQueryData(detail, { ...prev, isFavorite: !prev.isFavorite })
  C-->>V: UI flips immediately
  M->>API: toggleFavoriteRequest(id)
  alt success
    API-->>M: TrackDto
    M->>C: invalidateQueries(all + detail)
  else failure
    API-->>M: Error
    M->>C: rollback to snapshot
  end
```

Implementation skeleton:

```ts
useMutation<Track, Error, string, { previousDetail?: Track }>({
  mutationFn: async (id) => toTrack(await toggleFavoriteRequest(id)),
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: tracksKeys.detail(id) });
    const previousDetail = queryClient.getQueryData<Track>(tracksKeys.detail(id));
    if (previousDetail) {
      queryClient.setQueryData<Track>(tracksKeys.detail(id), {
        ...previousDetail,
        isFavorite: !previousDetail.isFavorite,
      });
    }
    return { previousDetail };
  },
  onError: (_e, id, ctx) => {
    if (ctx?.previousDetail) queryClient.setQueryData(tracksKeys.detail(id), ctx.previousDetail);
  },
  onSettled: (_d, _e, id) => {
    queryClient.invalidateQueries({ queryKey: tracksKeys.all });
    queryClient.invalidateQueries({ queryKey: tracksKeys.detail(id) });
  },
});
```

## Mappers — why we bother

Wire shape (`TrackDto`) often differs from app shape (`Track`):

| DTO field          | Domain field      | Reason            |
| ------------------ | ----------------- | ----------------- |
| `duration_seconds` | `durationSeconds` | naming convention |
| `cover_url`        | `coverUrl`        | naming convention |
| `is_favorite`      | `isFavorite`      | naming convention |

The mapper is the only place that knows about both shapes; components only see `Track`. When the API changes (`duration_ms` instead of `duration_seconds`?), one file changes.

## When to call the API directly?

Almost never. Acceptable cases:

- One-off imperative calls (analytics flush at app close).
- Inside another `queries.ts` (e.g. you compose two endpoints into one hook).
- Tests.

If you find yourself reaching for `api.ts` from a component, you probably want a `useQuery` instead.

***

<small>Source: [`docs/data-fetching.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/data-fetching.md)</small>
