import "server-only"; import type { ApiResult } from "@/app/lib/types"; // Server-only client for solvway-mobile-api. Injects the secret `api-key`, // optionally forwards the member JWT as a bearer, and normalizes the various // upstream response shapes into a single ApiResult. export interface MobileCallOptions { method?: "GET" | "POST" | "PUT" | "DELETE"; body?: unknown; token?: string; headers?: Record; /** Upstream timeout; the mobile-api can block indefinitely (e.g. registerNewMember's * account-creation wait loop), and the UI must never hang on it. */ timeoutMs?: number; } const DEFAULT_TIMEOUT_MS = 30_000; /** The mobile-api signals an expired/invalid JWT with these specific responses. */ function isExpiredSignal(status: number, raw: string): boolean { const t = raw.toLowerCase(); return ( (status === 500 && (t.includes("expired token") || t.includes("invalid token"))) || (status === 400 && t.includes("missing header 'authorization'")) ); } function extractError(parsed: unknown): string | undefined { if (parsed && typeof parsed === "object") { const o = parsed as Record; return (o.errorMessage as string) || (o.message as string) || undefined; } if (typeof parsed === "string" && parsed.trim()) return parsed; return undefined; } export async function callMobileApi( path: string, opts: MobileCallOptions = {}, ): Promise> { const base = process.env.MOBILE_API_BASE_URL; const key = process.env.MOBILE_API_KEY; if (!base || !key) { return { ok: false, error: "Mobile API is not configured" }; } const headers: Record = { "api-key": key, ...(opts.headers ?? {}), }; if (opts.token) headers["Authorization"] = `Bearer ${opts.token}`; if (opts.body !== undefined) headers["Content-Type"] = "application/json"; let res: Response; try { res = await fetch(`${base}${path}`, { method: opts.method ?? "GET", headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, cache: "no-store", signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS), }); } catch (err) { if (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")) { return { ok: false, error: "The server is taking too long to respond. Please try again.", timedOut: true, }; } return { ok: false, error: "Unable to reach the server. Please try again." }; } const raw = await res.text(); let parsed: unknown = undefined; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = raw; } } if (!res.ok) { if (isExpiredSignal(res.status, raw)) { return { ok: false, error: "Your session has expired. Please sign in again.", status: res.status, expired: true, }; } // Unverified member: mobile-api marks it with a header (body text unreliable; other 403s exist). if (res.status === 403 && res.headers.get("x-phone-verification-required") === "true") { return { ok: false, error: "Phone verification required.", status: 403, phoneVerificationRequired: true, }; } return { ok: false, // Never surface an empty body or raw upstream JSON (e.g. Spring's default 500) to the page. error: extractError(parsed) ?? "Something went wrong. Please try again.", status: res.status, }; } // 2xx, but the body may still encode a logical failure. if (parsed && typeof parsed === "object") { const obj = parsed as Record; if (obj.result === "false") { return { ok: false, error: (obj.errorMessage as string) || (obj.message as string) || "Request failed", extra: obj, }; } if (obj.success === false) { return { ok: false, error: (obj.message as string) || "Request failed", extra: obj, }; } } return { ok: true, data: parsed as T }; }