API Client¶
Tomoda has no HTTP library — every network call uses the platform's built-in fetch. utils/api.ts provides a tiny error-handling wrapper, utils/tokenManager.ts keeps the bearer token in-memory, and services/*.ts modules expose typed functions, one per backend domain. The services are pure transport (no React imports); TanStack Query sits on top of them and owns the cache — see Data layer.
Files at a glance¶
| File | Role |
|---|---|
utils/api.ts |
API_URL, WS_URL, WEB_URL constants; handleResponse; emitSessionExpired; fetchWithTimeout |
utils/apiFetch.ts |
apiFetch(path, init?) — authenticated fetch with a request timeout and reactive 401 → refresh → retry; apiJson(path, init?) — apiFetch + handleResponse in one call |
utils/apiErrors.ts |
ApiError, NetworkError (status 0, timedOut), localizeApiError |
utils/tokenManager.ts |
In-memory token cache + proactive refresh (on setup, a 4-minute timer, and app-foreground) |
contexts/AuthContext.tsx |
Owns the bearer; consumes AUTH_SESSION_EXPIRED |
services/*.ts |
One module per backend domain (pure transport, owns enum unions) |
lib/queryClient.ts |
TanStack Query client singleton + default options |
hooks/use*.ts |
One query hook per cacheable resource + its <thing>QueryKey |
URL resolution¶
utils/api.ts resolves URLs lazily so dev / prod / per-platform overrides work without rebuilding:
const getApiUrl = () => {
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
if (apiUrl && apiUrl.trim() !== '') return apiUrl;
return 'http://127.0.0.1:8080/api/v1';
};
export const API_URL = getApiUrl();
export const WS_URL = getWsUrl(); // ws://127.0.0.1:8080/ws by default
export const WEB_URL = process.env.EXPO_PUBLIC_WEB_URL?.replace(/\/$/, '')
|| 'https://tomoda.life';
Production injects these at build time (https://api.tomoda.life/api/v1, wss://api.tomoda.life/ws): the web bundle via --build-args in .github/workflows/images.yml (frontend/Dockerfile), native binaries from frontend/.env + frontend/scripts/release/build-with-secrets.sh.
handleResponse¶
Every service call funnels its Response through handleResponse. It:
- Parses an error body on non-2xx and surfaces the server's
error.message(or falls back toHTTP <status>). - On 401 with a token-related error code (
TOKEN_EXPIRED,TOKEN_INVALID,AUTH_REQUIRED, or no code at all), throws aSessionExpiredErrorso the root layout's unhandled-rejection handler swallows it. It does not emitAUTH_SESSION_EXPIREDitself: a 401 only reacheshandleResponseafterapiFetchhas already tried a refresh + retry and emitted on give-up (see Refresh on 401). - Reads the body as text first — returns
nullfor empty responses, otherwise parses JSON (falling back to raw text for non-JSON payloads).
const emitSessionExpired = () => {
const now = Date.now();
if (now - _sessionExpiredAt < 2000) return; // 2s debounce
_sessionExpiredAt = now;
DeviceEventEmitter.emit(AUTH_SESSION_EXPIRED);
};
A 2-second debounce prevents a burst of failing requests from re-emitting the event repeatedly while logout is in flight.
AuthContext listens for AUTH_SESSION_EXPIRED and calls logout():
const subscription = DeviceEventEmitter.addListener(
AUTH_SESSION_EXPIRED,
() => { void logout(); }
);
logout() clears local state first (in-memory token, user, query cache), then sends POST /auth/logout in the background with a 5 s timeout and clears storage. A slow or offline network never holds the user on a dead session. It is a no-op once signed out, so repeated session-expired events produce one sign-out and one logout request.
Building requests¶
Authenticated service calls go through apiJson(path, init?), the apiFetch + handleResponse shape nearly every service method wants. apiFetch injects the bearer + JSON headers (merged over any caller headers) and owns the reactive refresh (see Refresh on 401); apiJson funnels its Response through handleResponse and returns the typed body. A typical call:
return apiJson<Chat[]>('/chats');
path is relative to API_URL (apiFetch prepends it), or a full URL. Reach for apiFetch directly only when the caller inspects the raw Response (res.status / res.ok), then funnel it through handleResponse by hand. Every API-host call that carries the bearer token goes through apiFetch, including the authenticated /auth/* routes (profile, password, username, name, links, email change, export, delete). Intentionally unauthenticated calls carry no auth header, since a 401 there is a credential error, not a stale session: login, register, social login, passkey and public projections like /events/:id/public use apiFetch(..., { anonymous: true }); refresh, logout, OTP and password reset use fetchWithTimeout. Login, register and social login reject with an ApiError carrying the backend message (or the call's fallback copy when the body is not the JSON envelope, such as an HTML 502), and with a NetworkError on a timeout or no response.
Network and offline contract¶
Every HTTP call from app/, components/, hooks/, contexts/ and services/ goes through apiFetch / apiJson; ESLint (no-restricted-globals, no-restricted-imports in eslint.config.js) rejects a raw fetch, new WebSocket or fetchWithTimeout there. The allowlisted owners are the refresh, logout, OTP and password-reset calls in authService.ts and sessionRefresh.ts, the storage transfers in presignedUpload.ts and the chat photo download, and the two socket owners (contexts/WebSocketContext.tsx, services/chatService.ts). A public endpoint calls apiFetch(path, init, { anonymous: true }): no bearer, and a 401 comes back as-is with no refresh.
| Situation | Behavior |
|---|---|
| App opens offline | Every read is a persisted useQuery, so screens paint their last data |
| Slow link | Cached data renders at once; the refetch runs in the background |
| Background load or refetch fails | Cached content stays; no toast |
| First load fails, nothing cached | The screen's error state with retry, never its empty or getting-started content; the list refetches on foreground, reconnect (socket or HTTP back online) and screen focus |
| Requests stop getting responses and the device has no network | One app-wide "Off the grid. Reconnecting…" pill, floating at the bottom above the dock, once the OS reports the internet unreachable, or, when it has no answer, transport failures (no response in between) have lasted 5 s (with the internet reachable, the server being unreachable shows the screens' own error and retry states instead). Client timeouts never count. It hides after 3 s of responses with no failure, so an intermittent link doesn't flap it. Tapping it hides it for 60 s, even if the link recovers and drops again meanwhile. Chat rooms show their own status instead |
| User action fails | A toast with actionErrorMessage(e, t, fallback) (the connection message for a network failure, the action's own copy otherwise); the input is kept |
| Long operation | An explicit timeoutMs (data export: 60 s) |
| Image fails to load | AssetImage shows its placeholder, retries once after 2 s, then on each return online, up to 3 retries |
Token refresh¶
utils/tokenManager.ts keeps the access token in module-level memory so the hot path (every request) skips disk:
let _cachedToken: string | null = null;
export const getCachedToken = async () => {
if (_cachedToken !== null) return _cachedToken;
_cachedToken = await getAccessToken(); // utils/tokenStore.ts
return _cachedToken;
};
AuthContext keeps the cache in sync via setCachedToken() / clearCachedToken() on every login mutation. clearCachedToken() also bumps a generation counter, so a refresh still in flight when the session ends (sign-out or an account switch) drops its result instead of seating a token on the next session. Persistence funnels through utils/tokenStore.ts, the single seam for the access + refresh token, so the OS-share handler can later read them from a shared Keychain access group.
Refresh is proactive, not request-driven. setupTokenRefresh() runs a check on three triggers so a request rarely has to eat a 401 and reactively refresh: once immediately (covering a cold boot whose stored access token expired while the app was closed), on a 4-minute timer, and whenever the app returns to the foreground (where JS timers were suspended):
// setupTokenRefresh() — runs while token + refreshToken are present
const checkAndRefresh = async () => {
if (await isTokenExpiringSoon()) await refreshCallback(); // < 5 min remaining
};
void checkAndRefresh(); // cold boot
const interval = setInterval(() => { void checkAndRefresh(); }, 4 * 60 * 1000);
const sub = AppState.addEventListener('change', s => { if (s === 'active') void checkAndRefresh(); });
The callback is AuthContext.refreshAccessToken, which calls apiFetch's refreshOnce(): the one single-flight shared by the proactive check, reactive 401s and the realtime socket handshake, so they never refresh in parallel. It updates the context token only on 'refreshed' and signs out only on 'rejected'; 'transient' keeps the session for the next check.
isTokenExpiringSoon() decodes the JWT with jwt-decode and returns true when exp is within 5 minutes.
Refresh on 401¶
The proactive refresh (fired on setup, every 4 minutes, and when the app returns to the foreground) is the top-up; apiFetch is the reactive safety net for abrupt expiry (clock skew, server-side revocation, a request fired right after a backgrounded resume). On a refreshable 401 apiFetch:
- Confirms the request isn't a public token endpoint (
isAuthEndpoint: login, register, Google/Apple login, refresh, logout, reset-password,otp/*,webauthn/login/*; a 401 there is a wrong credential, not a stale token) and that the 401 isn'tREAUTH_FAILEDorSTEP_UP_FAILED(a wrong password, OTP or passkey re-entered for account deletion, data export or a step-up, which the caller shows as a credential error). A request also stops refreshing, retrying and reporting session expiry once the session epoch (bumped on sign-out and on entering or leaving a linked account) has moved on since it was sent. - Retries straight away, without refreshing, when the cached token is no longer the one the request was sent with (a refresh landed while it was queued or in flight). Otherwise it runs a single-flight
refreshOnce(): concurrent 401s dedupe onto one in-flightauthService.refreshSession(refreshToken)(pure, no React). The new access token is seated in memory (setCachedToken) before it is persisted totokenStore, so a failed write can't strand requests on the old token. The whole flight is capped at 20 s and resolves'transient'past that, so a hung token-store read can't pin every waiting caller. - Retries the original request once with the new token.
Refresh always uses the active session's chain (activeRefreshToken in utils/linkedSession.ts), so a linked session refreshes its own token and never writes into the personal store. Only when the session is genuinely dead (no refresh token, the server refuses the refresh token with a 401, or a 403 whose JSON body carries AUTH_REQUIRED, TOKEN_EXPIRED or TOKEN_INVALID, or the retried request also 401s) does apiFetch emit AUTH_SESSION_EXPIRED, which AuthContext turns into a logout, or for a linked session into a drop back to personal. Any other refresh failure (5xx including the server's 503 when it can't check the token, 429, any other 403 such as an edge or WAF page, other 4xx, network, timeout) is transient and surfaces as a retryable NetworkError: the refresh token is almost certainly still good, so the session is preserved rather than logging the user out on a blip. A successful refresh + retry is invisible to the caller; the user is never bounced to /auth/login.
Global fetch¶
The app's global fetch is React Native's, because Expo's native fetch is unreliable on devices. metro.config.js sets EXPO_PUBLIC_USE_RN_FETCH=1 before the bundler starts, which covers the dev server, release builds and published updates; a test guards it.
Request timeout and network errors¶
At most six apiFetch requests are in flight at once (MAX_IN_FLIGHT); the rest wait in FIFO order, and a caller abort while queued rejects at once without sending. apiFetch bounds every request with a client timeout (DEFAULT_TIMEOUT_MS, 15 s, or the caller's timeoutMs) whose budget covers queue wait, flight and reading the body: a request still queued when its budget runs out rejects as a timed-out NetworkError and leaves the queue without sending, and a body that stalls after the headers arrive rejects the same way from res.json() / res.text() (the queue slot frees once headers arrive). The timeout runs through an AbortController chained to any caller-supplied signal; the auth endpoints that bypass apiFetch use fetchWithTimeout for the same ceiling. A fetch-level failure or a timeout rejects as a NetworkError (status: 0, timedOut), which TanStack Query retries and localizeApiError maps to the network / timeout copy. Without this a stalled connection would hang the promise forever and pin a spinner that never resolves.
Below the JS queue, the native HTTP stack allows 8 connections per host on both platforms (frontend/plugins/with-network-limits.js): the app uses React Native's fetch, so iOS applies httpMaximumConnectionsPerHost through RN's NSURLSession configuration provider and Android sets the OkHttp dispatcher's maxRequestsPerHost. RN's cookie handling and HTTP cache are unchanged.
Sequence — a single request with auto-refresh¶
apiFetch's single-flight refresh + one retry, and only a failed refresh (no token, rejected, or a second 401) emits the debounced AUTH_SESSION_EXPIRED that logs the user out.Service modules¶
frontend/services/ holds one module per backend domain (a few domains split across two files where the surface is large). Each is a flat collection of async functions that return the parsed body (or throw on failure).
| Service | Backend domain | Endpoints / notable exports |
|---|---|---|
backstageService.ts |
backstage | /backstage/*: getMe (capabilities), Today stats, People search/detail/actions, audit search, report triage, cover submission review (/backstage/geo-covers with an area or place filter, favouriteCover, decideCover carries the server message on a 422), Tomoda accounts and invites, partner workspaces. Changes send the step-up token in the X-Step-Up-Token header (the gate spends it); refusals surface as ApiError codes |
reportService.ts |
report | POST /reports, one moderation notice and its review request. reportReasonsFor(type) returns the reason list the server accepts for a target: the member reasons, or the four cover reasons for a geo_cover target |
geoCoverService.ts |
geocover | GET /geo-covers/moments, /geo-covers/photos, /geo-covers/mine, POST /geo-covers/submissions and /submissions/{id}/withdraw, photo upload via uploadViaPresign('geo-cover', …); owns GeoCoverKind (area kinds plus place) and the <kind>:<key> place reference helpers. A second pending photo for a place is refused with ALREADY_SUBMITTED (isAlreadySubmitted) |
chatService.ts |
chat | /chats/* REST + the per-room WebSocket; chatService singleton. See Real-time |
chatOffline.ts |
chat (device only) | chatOutbox (unconfirmed sends) and chatHistory (newest page per chat) in AsyncStorage; clearChatDeviceData on sign-out and sign-in. See Real-time |
discoveryService.ts |
discovery | /discovery/map, /discovery/radar, /discovery/locations/:id, /discovery/search (NL intent), /discovery/search/users, /discovery/profiles/:id (full profile card), profile booklet pages /discovery/profiles/:id/{journal,atlas,atlas/:country,atlas/:country/regions} (getUserJournal is cursor-paginated trip/day/single segments of place-stops; getAtlasRegions returns a country's admin-1 provinces with GeoJSON boundaries, fetched on demand per country for the map drill), getFeed(lat,lng) → /discovery/feed (home feed: moments tray + events). Event/moment detail proxy to /events/:id/detail and /moments/:id |
searchService.ts |
discovery + plan + location | events()/locations() hit /discovery/search/{events,locations} (the latter takes a kinds allowlist); saved-area pin GET/PUT /discovery/pin; saveLocation posts /items/save-location (plan); resolvePlace posts /locations/resolve (location) |
taxonomyService.ts |
discovery | /discovery/taxonomy, /discovery/taxonomy/resolve |
eventService.ts |
event | events CRUD + RSVPs; event-items board via getEventItems / createEventItem / updateEventItem / deleteEventItem / reorderEventItems on /events/:id/items. EventItemInput.photo_keys?: string[] carries uploaded asset keys (cover first); a list replaces the item's photos, omit on update to preserve existing ones |
eventCheckinService.ts |
event | /events/active/nearby, POST /events/:id/checkin (arrival proximity match) |
friendService.ts |
friend | /friends/* graph, requests, close-friends, people-you-may-know suggestions and dismissals; user search proxies to /discovery/search/users |
planService.ts |
plan | /plans/* canvas, poll, members, promote; /users/:userId/plans |
itemService.ts |
plan | /items/* stash + plan board items |
momentService.ts |
moment | /moments/* ephemeral posts |
checkinService.ts |
presence | /checkins, /checkins/me, /checkins/recent, getCheckinDetail(id) (chat link-preview CheckinCard), untagCompanion(id, 'me' \| userId) |
locationService.ts |
location + presence | fetchNearbyPlaces(lat, lng, radius, intent?, q?) → /locations/nearby (capture picker list, fillNeeded, per-chip intentCounts, and the chip typed text resolved to); fillNearbyPlaces(lat, lng, radius, intent?, page?) → POST /locations/nearby/fill; searchMorePlaces({q, scope, lat?, lng?, countryCode?, auto?, surface}) → POST /locations/search-more (a lookup for a place the free search missed; scope is nearby, area or global; a refusal still returns the catalog matches with a status); reportSearchMorePick(surface) → POST /locations/search-more/picked (metrics only); searchNearbyLocations(lat, lng, radius=150, limit?) → /locations/nearby (browse surfaces such as planner recommendations); autocompleteLocationsPage(query, lat?, lng?, limit=5, kinds=['poi'], {surface?, signal?}) → /locations/nearby/autocomplete, returning {results, fallback} where fallback is eligible or none (autocompleteLocations is the results-only wrapper; the kinds allowlist defaults to ['poi']; add settlement/address/residential to widen); resolveLocation(candidate) → /locations/resolve; reverseCity(lat, lng) → /locations/reverse; plus /location/update, /location/friends, /presence/* active-location + heartbeat |
notificationService.ts |
notification | /notifications/* inbox, /push-tokens device registration |
activityService.ts |
activity | Client interaction-logging framework. Transport buffers events and batch-POSTs /activity/events (flush on a 10s idle timer, at 100 events, or on app backgrounding; best-effort, per-verb sampling). tracker(surface) returns typed helpers (impression/select/view/dwell/tap/dismiss/search) so a screen logs without repeating the surface. Reusable hook: useImpressionTracker (spread onto a FlatList/FlashList to log the shown-but-not-picked negatives with rank on viewability, e.g. the search results list) |
partnerService.ts |
partner | /partner/*, /partners/*, /me/* partner membership |
linkPreviewService.ts |
media | /link-preview URL unfurl (8 s timeout, cancellable). Chat cards read it through hooks/useLinkPreview.ts (one query per URL; a miss is cached 60 s). Typed cards retry network errors and 5xx, and treat only 404/403 as gone |
klipyService.ts |
/klipy/config (ours), then api.klipy.com directly |
Klipy requires API and media requests from the device, so listings go straight to Klipy with plain fetch (the one place outside apiFetch, since it is not our API). GET /klipy/config supplies {ads_enabled, api_key, customer_id} once per session (memory only). Calls: trending and search (with customer_id, per_page, page, locale), recent ({type}/recent/{customer_id}), and fire-and-forget share (on send) and view (first time a received item's bubble mounts, once per message per session). Native sends the WebView user agent as User-Agent. Results render in Klipy's order and composition and are never cached client-side, so every picker open fetches fresh. Opening a chat starts the page-1 GIF and Sticker Trending requests (warm); the picker uses them once and only within 60 seconds and for the same ad width, otherwise it fetches again. Under the search field a single-line row of 32 dp chips offers Recent, Trending and a fixed set of line-icon chips (CATEGORY_CHIPS in gifChips.ts, all outline icons from one family: LOL, Love, Hello, Yes, No, Thank you, Sad, Congrats, Birthday, Hugs) for GIF, Sticker and Meme (the bottom tabs; memes are Klipy's static-memes type and render as still images); there is no categories request, so the row is static and never waits on the network. A category chip runs Klipy's normal search for its localized term (chat.gif.chip_*_query, labels in chat.gif.chip_*), and the row is dimmed while the search field has text. Each time the picker opens, both GIF and Sticker open on Trending; within that session a type keeps the chip last picked until the picker closes. When ads are on, requests add the ad-* params (klipyAds.ts): min 50x50, max width the row width (window width less the grid padding), max height 200, plus OS, device, language, pixel ratio and ad-connection-type (wifi 2, ethernet 1, cellular 3, otherwise 0, read per request through expo-network, loaded lazily so a binary without the native module sends 0). The grid is two aspect-correct columns and each tile goes into the shorter column. An ad is scaled uniformly to the column width from its declared size (never upscaled, never cropped); if that leaves it at least 90 dp tall (AD_TILE_MIN_HEIGHT) it is a tile in the column, otherwise a tight full-width row at native size, both with a small "Ad" tag and the tile corner radius. The slot is sized from the declared size before the creative loads, so nothing shifts. Klipy's order is kept except for spacing (placeAds): no ad before the 6th content result and at least 4 content results between ads (never adjacent): a displaced ad moves to the next allowed slot, order is kept and none is dropped (with fewer than 6 results they go last once the list is complete). The creative is wrapped with minimal CSS (buildAdHtml) so it blends with the tiles. Each ad's WebView mounts (and so counts the impression) only once its row has scrolled into view, once per ad. Ads are never sent, shared or tracked. Each Klipy call has a 10 second ceiling (body read included) and the picker aborts a superseded request, so a slower older response can never overwrite newer results. A failed request (KlipyPage.failed) shows an error with a retry button in the picker, distinct from a real empty result; Klipy failures never feed the app's offline state, since they do not go through apiFetch |
presignedUpload.ts |
media | uploadViaPresign runs POST /uploads/<kind> → PUT for avatar, group-avatar, chat-image, moment, item-image, event-cover, plan-cover, geo-cover. uploadChatImagesBatch(uris, roomId) runs POST /uploads/chat-image/batch then PUTs in parallel |
legalService.ts |
auth | GET /auth/legal/versions, GET /auth/legal/status; owns the LegalDoc union and the accepted_*_version clickwrap fields that authService.register and profile completion also send |
userService.ts |
user | lean GET /users/:id (mention chips), /auth/profile read/update, avatar rotate/remove |
storageService.ts |
(local) | save(key, val) / load(key) + StorageKeys local cache |
chatService.ts is the largest — it owns the WebSocket lifecycle in addition to REST. See Real-time.
Data layer¶
The services above are the transport. The cache, dedup, and revalidation on top of them are TanStack Query (@tanstack/react-query). Route files don't call services directly for reads; they consume a query hook.
- Client singleton:
frontend/lib/queryClient.ts. Defaults:staleTime: 30_000,gcTime: 24 h,refetchOnWindowFocus: true. Retries: up to 2 (1 after a client timeout); none for a dead session or a 4xx except 408 and 429. The delay honors the response'sRetry-After(seconds or an HTTP date, capped at 30 s;apiJsonattaches it to the thrown error), else exponential backoff with jitter.PersistQueryClientProvidermounts outermost inapp/_layout.tsx. - The cache is persisted to disk (
createAsyncStoragePersister, keytomoda-query-cache). On launch the last-known cache is restored so every screen paints immediately and revalidates in the background, instead of blocking on a spinner.gcTimematches the 24 h persistmaxAgeso restored queries survive hydration; the cache is busted on an app-version change and cleared on logout (memory + disk). Only settled, successful queries are persisted, and an infinite list keeps at most its first 3 pages on disk and on restore, so launch paints quickly; deeper pages reload as the user scrolls. - One hook per cacheable resource in
frontend/hooks/(useMoment,usePlanDetail,useEventDetail,useUserProfile,useStashItems, …), each exporting its own<thing>QueryKeytuple factory next to it. There is no central query-key file — invalidation sites import the key name from the domain hook. - Reads are keyed by the service call; the
queryFnis the service function.refetchOnWindowFocusis on:focusManageris wired to React NativeAppStateinapp/_layout.tsx, so returning to the foreground refetches stale (only) queries in the background. Screen-navigation refetch stays opt-in viahooks/useRefetchOnFocus.ts. - WebSocket-driven freshness: socket handlers
invalidateQueriesorsetQueryDatainstead of every consumer refetching. A WS-hydrated query (chat-unread, friends, taxonomy) carries the authoritative value viasetQueryData, runsstaleTime: Infinity, and reconciles only on a reconnect gap. See State Management → Data layer. - Infinite lists refresh only their head (
hooks/useHeadRefresh.ts, helpers inlib/infiniteList.ts). They turn off the foreground, reconnect and mount refetch (infiniteListOptions), since that re-requests every loaded page in sequence; a list with nothing loaded (a failed first load) still refetches on foreground, reconnect and screen focus, and an invalidated list refetches in full on mount. Instead, on mount (including a cold start from the persisted cache), app foreground, reconnect (the query cache's reconnect pass, run when the socket recovers and whenutils/connectivitygoes back online) and screen focus, a list past itsstaleTimefetches its first page throughapiFetch, one request per list across every mount. The fresh head replaces page 0, items that moved up are dropped from the later pages, and later pages, untouched rows and the scroll position stay as they are. Only the focused screen refreshes; a blurred one waits for its next focus, and a blur cancels an in-flight head fetch. - The feed merges a fresh head at once when the viewer is on the first moment, with the visible card anchored. Scrolled down, the head waits behind a "New posts" pill: tapping it scrolls to the top and reveals the merged head, and reaching the top on their own applies it too. Back after more than 30 minutes in the background, the feed restarts at a fresh first page and scrolls to the top, showing the cached content until that page lands.
- Other refresh paths stay: pull-to-refresh, live socket patches, and invalidation at the write site (posting a moment refreshes the feed and the author's moments and journal, saving an event refreshes the feed and the host's upcoming events, a drained OS share refreshes the stash).
- Errors funnel to
components/ui/AppErrorBoundary.tsx(QueryErrorResetBoundary+ themed, Sentry-reported Retry).
Lean vs full user fetch¶
Fetching a user comes in two shapes:
| Need | Call | Shape |
|---|---|---|
| Mention chip, live-handle URL, quick label | userService.resolveMention(id) → GET /users/:id |
{ id, name, username, avatar_url, bio, is_friend } |
| Full profile card (moments, events, mutuals, friendship state) | discoveryService.getUserProfile(id) → GET /discovery/profiles/:id |
aggregated UserProfile (optional auth; viewer-relative fields when authed) |
The lean card is the hot path for chat and composer chips; userService memoizes it per id for five minutes and shares one in-flight fetch. The aggregated profile lives in the discovery domain because it joins across moments, events, and the friend graph.
Conventions¶
- Auth header:
Authorization: Bearer ${token}only — no cookies. - Content-Type:
application/jsononPOST/PATCH/PUT. Asset uploads (avatar, group avatar, chat image, moment media, board-item photos, event cover, plan cover) go throughpresignedUpload.ts.POST /uploads/{kind}returns a 5-minute presigned PUT URL with Content-Type AND Content-Length signed in, the client PUTs the bytes directly to S3, then finalises on the matching resource endpoint (PUT /users/me/avatar,PUT /chats/{id}/avatar,POST /moments,POST /itemswithimage_keys, orPOST /chats/{id}/messageswithimage_keys). On native, PUT goes through anexpo-file-systemupload task (RN fetch with a Blob from afile://URI silently fails on iOS NSURLSession). A stall watchdog cancels the task after 30 s without upload progress and rejects with a timed-outNetworkError; a slow upload that keeps sending bytes runs to completion. On web, fetch reports no upload progress, so the PUT gets a 120 s ceiling instead. Both upload helpers take anAbortSignalthat cancels the presign and the PUT. - Errors: every service call resolves through
handleResponse(directly, or viaapiJson); never branch onresponse.okmanually. - Token reads: always
await getCachedToken()on the hot path; persistence goes throughutils/tokenStore.ts, neverAsyncStorage.getItem('@auth_token')directly. - Caching lives in Query, not the services: TanStack Query is the app-wide read cache and stale-while-revalidate layer (see Data layer). A few services (
chatService,getChatRooms) additionally persist their own copy viastorageServicefor offline-first cold starts; the realtime chat message stream stays outside Query by design.
Network chaos tests¶
frontend/__tests__/network/ drives the real apiFetch, request queue, connectivity signal, session refresh, chat socket and chat outbox through a fault-injection fetch and a fake WebSocket, on fake timers. It asserts invariants (every request settles inside its budget, one refresh per 401 burst, no queue slot leaked, no duplicate or reordered chat sends), not call sequences.
cd frontend
npm run test:network # chaos tests
npm run bench:network # benchmarks
| Scenario | Invariant |
|---|---|
| Lossy link, 15% of requests stall 5-15 s | Every request settles within its timeout; failures are timed-out NetworkErrors; at most 6 in flight |
| 20 concurrent 401s | Exactly one /auth/refresh; each request retried once; no sign-out |
| Refresh answers 5xx, 429, resets or stalls | Session and refresh token kept; callers get a retryable NetworkError |
| Aborts, timeouts, resets and throws mixed | No queue slot leaks; a long request cannot hold a short one past the short one's own timeout |
| Offline then online | The pill needs real transport failures, ignores timeouts and aborts, clears on the first response, and a dismissal lasts one offline streak |
| Server restart | The chat socket backs off to a 30 s cap and reconnects after the server returns; the outbox flushes once, in order, and a send that reached the server before timing out is not stored twice (client_msg_id) |
Test doubles: faultFetch.ts scripts per-request outcomes (delay, hang until abort, connection reset, slow body, any status, fail N times then succeed); fakeSocket.ts is the chat socket with drops, delayed opens and server restarts. Benchmarks report queue overhead per request, startup fan-out time to all settled (p50/p95, with and without 10 s stalls), a refresh storm and a 200-message outbox flush. Changes to the network layer keep npm run test:network green.
Cross-links¶
- State Management —
AuthContextis where the bearer lives - Real-time — the WebSocket counterpart for chat
- Backend API conventions — server-side contract