Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit 03189ee · 15 days ago

Expo, Part 3: Backend Communication — API Client, Real-Time via SSE, Bugs, and Offline

🌐 Machine-translated from Russian. Show original

In this part:

Principles#

  1. One API client for the entire application: headers, token, errors — all in one place.
  2. Clear errors to the user: "No connection to the server," not TypeError: Network request failed.
  3. Real-time, only while the app is open; push notifications in the background (part 4).
  4. After the connection loss — reread the data: messages may have arrived during the interruption.

API client#

import Constants from 'expo-constants';

export const API_URL: string =
  (Constants.expoConfig?.extra?.apiUrl as string | undefined) ?? 'https://itgov.kz';

export class ApiError extends Error {
  constructor(message: string, readonly status: number) {
    super(message);
  }
}

let onUnauthorized: () => void = () => {};
export const setUnauthorizedHandler = (fn: () => void) => { onUnauthorized = fn; };

type Init = { method?: 'GET' | 'POST' | 'DELETE'; json?: unknown; form?: FormData; auth?: boolean };

export async function api<T>(path: string, init: Init = {}): Promise<T> {
  const headers: Record<string, string> = { Accept: 'application/json' };
  if (init.auth !== false && token) headers.Authorization = `Bearer ${token}`;
  let body: string | FormData | undefined;
  if (init.form) body = init.form;
  else if (init.json !== undefined) {
    headers['Content-Type'] = 'application/json';
    body = JSON.stringify(init.json);
  }
  let r: Response;
  try {
    r = await fetch(`${API_URL}${path}`, { method: init.method ?? (body ? 'POST' : 'GET'), headers, body });
  } catch {
    throw new ApiError('Нет связи с сервером. Проверьте интернет.', 0);
  }
  const data = (await r.json().catch(() => ({}))) as { error?: string };
  if (r.status === 401 && init.auth !== false) onUnauthorized();
  if (!r.ok) throw new ApiError(data.error ?? `Ошибка сервера (${r.status})`, r.status);
  return data as T;
}

What is important here:

  • status 0 — "no network": screens show a separate message and a "Repeat" button;
  • 401 — token revoked (site logout, account deletion, blocking): global handler returns to login;
  • error text — from the server ({ error: "..." }), already in Russian and understandable to humans;
  • auth: false to the login request — so that an incorrect password does not trigger "exit."

Server: separate mobile API#

Mobile routes /api/m/* on the portal:

MethodPurpose
POST /api/m/auth/login, /logoutentry and exit
GET /api/m/meprofile and number of unread
GET /api/m/conversationslist of dialogues
GET /api/m/conversations/:id?before=messages with page-by-page loading "up"
POST /api/m/conversations/:id/messages, /read, /blocksend, "read," block,
POST /api/m/messages/:id/reportcomplaint about the
GET /api/m/users?q=search for a conversation partner
POST/DELETE /api/m/pushregistering and disabling push
DELETE /api/m/accountdeleting the

Why a separate API instead of the same routes as the site: a different login method (token instead of cookie), more compact responses, and the ability to change the site without breaking the app versions already installed on people. Old versions live on phones for months — the API must remain backward compatible: add new fields, don't delete old ones, and don't change their meaning.

Loading images#

export async function uploadImage(uri: string, mime = 'image/jpeg') {
  const form = new FormData();
  const ext = mime.split('/')[1] ?? 'jpg';
  form.append('file', { uri, name: `photo.${ext}`, type: mime } as unknown as Blob);
  return api<{ url: string; width: number; height: number }>('/api/upload', { form });
}

React Native accepts the { uri, name, type } object as FormData — this is its feature, hence the typecast. The server recodes the image and deletes the EXIF (which includes survey coordinates) — don't rely on the client to do this itself.

Real-time: SSE via XMLHttpRequest#

For chat, you need to instantly receive new messages and read marks. Options:

MethodProsCons
Polling once every N secondssimplydelay and unnecessary load
WebSocketbidirectional, has a separate server/protocol in React Native, more complex than proxy
Server-Sent Events (SSE)regular HTTP, the site server already knows howReact Native does not have a built-in EventSource

The site already had an SSE stream /api/messages/stream, so we left it and taught it to accept Authorization: Bearer. Instead of EventSource use XMLHttpRequest: in React Native responseText grows as data comes in while the connection is open.

export function openStream(token: string, onReconnect?: () => void): () => void {
  let xhr: XMLHttpRequest | null = null;
  let closed = false;
  let retry: ReturnType<typeof setTimeout> | undefined;
  let first = true;

  const connect = () => {
    if (closed) return;
    let seen = 0;
    let buf = '';
    const x = new XMLHttpRequest();
    xhr = x;
    x.open('GET', `${API_URL}/api/messages/stream`);
    x.setRequestHeader('Authorization', `Bearer ${token}`);
    x.setRequestHeader('Accept', 'text/event-stream');
    x.onreadystatechange = () => {
      if (x.readyState === 3 || x.readyState === 4) {
        const text = x.responseText ?? '';
        const r = parseSse(buf + text.slice(seen));   // берем только новую часть
        seen = text.length;
        buf = r.rest;                                   // незаконченное событие ждет продолжения
        r.events.forEach(emit);
      }
      if (x.readyState === 2 && x.status === 200) {
        if (!first) onReconnect?.();                    // после обрыва — перечитать данные
        first = false;
      }
      if (x.readyState === 4 && !closed) retry = setTimeout(connect, x.status === 401 ? 60_000 : 5_000);
    };
    x.send();
  };

  connect();
  return () => { closed = true; clearTimeout(retry); xhr?.abort(); };
}

Thread parsing is a separate clean function, easily covered by tests:

export function parseSse(chunk: string): { events: unknown[]; rest: string } {
  const blocks = chunk.replace(/\r\n/g, '\n').split('\n\n');
  const rest = blocks.pop() ?? '';
  const events: unknown[] = [];
  for (const block of blocks) {
    const data = block.split('\n')
      .filter((l) => l.startsWith('data:'))
      .map((l) => l.slice(5).replace(/^ /, ''))
      .join('\n');
    if (!data) continue;
    try { events.push(JSON.parse(data)); } catch { /* битое событие пропускаем */ }
  }
  return { events, rest };
}

Details we learned in practice:

  • reconnection with pause (5 s, at 401 — a minute), otherwise, if the server crashes, the phone will cause a "DDoS";
  • the server sends a ping comment : ping every 25 seconds — otherwise, the proxy or mobile operator will close the "silent" connection;
  • The server itself closes the stream every 30 minutes: upon reconnection, the token and locks are rechecked, and XHR's responseText does not grow indefinitely.

The stream is open only while the app is on the screen#

import { AppState } from 'react-native';

useEffect(() => {
  if (!enabled) return;
  let close: (() => void) | null = null;
  const start = () => { const t = getToken(); if (t && !close) close = openStream(t); };
  const stop = () => { close?.(); close = null; };
  start();
  const sub = AppState.addEventListener('change', (st) => (st === 'active' ? start() : stop()));
  return () => { sub.remove(); stop(); };
}, [enabled]);

In the background, the OS will still "lull" the connection, and it would drain the battery. When the app is minimized, a push notifies about new messages.

Offline and poor network#

  • Show the last loaded, not a blank screen: the dialog list in memory is not reset if an update error occurs.
  • Sending message: the button is blocked for the duration of the request (protection against double sending); in case of error, the text remains in the input field.
  • Repeats — only for secure requests (GET). Repeating POST without idempotency can create a duplicate.
  • Timeouts: for long requests, use AbortControllerso the screen doesn't "hang" indefinitely.

A full-fledged offline (local database, sending queue) is not needed by everyone: for portal chat, it's enough to "show what was there and honestly say there's no network." For an accounting application like WorkTime, where marks are made even without communication, a queue on the device is mandatory.

Channel security#

  • HTTPS only. Android by default prohibits unencrypted HTTP in release builds — and that's right.
  • Do not embed secret keys (payment API keys, database access) into the app: the APK is easy to unpack. All secrets are only on the server.
  • Limit the frequency of requests on the server (login, user search, complaints).

Checklist#

  • One API client: token, JSON, errors, 401
  • Clear messages without a network
  • The mobile API is backward compatible with older app versions
  • Real-time with reconnection and reread after a break
  • The thread closes when the application is collapsed
  • Images are transcoded on the server, EXIF is deleted
  • No secrets in the app code

Next — push notifications: Expo, part 4: push notifications — expo-notifications, FCM V1, APNs, and privacy.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.