v1.0.12 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 35589c6fda.

Data fetching

All server data flows through @tanstack/react-query. A single QueryClient is created in 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

Catalog — bundled from Google Sheet (build time)

The song catalog in 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), 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/:

Run manually after sheet edits:

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. 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.

See features/catalog.md for the full catalog contract.

QueryClient defaults

// 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 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/.

// 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:

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:

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).

Registration

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):

// app/_layout.tsx
import '@/core/entrySetup'; // ← top of file, side-effect import
// 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) 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

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.

// 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:

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

Optimistic update — toggle favorite

Implementation skeleton:

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 fieldDomain fieldReason
duration_secondsdurationSecondsnaming convention
cover_urlcoverUrlnaming convention
is_favoriteisFavoritenaming 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.