Files
co-lite/solvway-customer-portal/app/lib/server/mobileApi.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

132 lines
4.0 KiB
TypeScript

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<string, string>;
/** 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<string, unknown>;
return (o.errorMessage as string) || (o.message as string) || undefined;
}
if (typeof parsed === "string" && parsed.trim()) return parsed;
return undefined;
}
export async function callMobileApi<T>(
path: string,
opts: MobileCallOptions = {},
): Promise<ApiResult<T>> {
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<string, string> = {
"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<string, unknown>;
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 };
}