Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions frontend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
# Get your publishable key from https://dashboard.clerk.com
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_key_here

# Backend API URL
# For web/localhost: http://localhost:5000/api
# For Android Emulator: http://10.0.2.2:5000/api
# For Physical device (Expo Go): http://<YOUR_WIFI_IP>:5000/api
EXPO_PUBLIC_API_BASE_URL=http://localhost:5000/api
# Backend API URLs
# Primary: Vultr
EXPO_PUBLIC_API_PRIMARY=https://YOUR_VULTR_URL/api

# Fallback: Render
EXPO_PUBLIC_API_FALLBACK=https://YOUR_RENDER_URL/api

# Public web client used for shared journey links (not the landing website).
EXPO_PUBLIC_WEB_APP_URL=https://path-finder-webapp.vercel.app
141 changes: 98 additions & 43 deletions frontend/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,117 @@
const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL!;
const DEFAULT_TIMEOUT_MS = 60_000; // 60 seconds to allow for long LLM processing

import { fetch } from "expo/fetch";

export async function apiFetch<T>(
const PRIMARY_API_URL = process.env.EXPO_PUBLIC_API_PRIMARY!;
const FALLBACK_API_URL = process.env.EXPO_PUBLIC_API_FALLBACK;

const DEFAULT_TIMEOUT_MS = 60_000;

async function requestWithFallback(
endpoint: string,
options: RequestInit = {},
token?: string,
isMultipart: boolean = false
): Promise<T> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);

try {
const headers: Record<string, string> = {
...(options.headers as Record<string, string> ?? {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
};

if (!isMultipart && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
): Promise<Response> {
if (!PRIMARY_API_URL) {
throw new Error("Primary API URL is not configured.");
}

const urls = [
PRIMARY_API_URL,
...(FALLBACK_API_URL && FALLBACK_API_URL !== PRIMARY_API_URL
? [FALLBACK_API_URL]
: []),
];

const headers: Record<string, string> = {
...(options.headers as Record<string, string> ?? {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
};

if (!isMultipart && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}

let lastError: unknown;

for (let i = 0; i < urls.length; i++) {
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
DEFAULT_TIMEOUT_MS
);

try {
const baseUrl = urls[i].replace(/\/+$/, "");

const response = await fetch(
`${API_BASE_URL}${endpoint}`,
{
const response = await fetch(`${baseUrl}${endpoint}`, {
...options,
signal: controller.signal,
headers,
});

// Retry on gateway/service availability errors.
if ([502, 503, 504].includes(response.status) && i < urls.length - 1) {
console.warn(`Backend unavailable at ${baseUrl}. Trying fallback...`);
continue;
}
);

if (!response.ok) {
let message = await response.text();
// If the backend returns HTML (e.g. 404 Cannot GET), clean it up
if (message.includes("<!DOCTYPE html>") || message.includes("<html>")) {
if (response.status === 404) {
message = `Endpoint ${endpoint} not implemented on the backend yet.`;
} else {
message = `Server error ${response.status}: ${response.statusText}`;
}
} else {
try {
const jsonError = JSON.parse(message);
message = jsonError.error || jsonError.message || message;
} catch {
// keep as raw text
return response;
} catch (err: any) {
lastError = err;

if (i === urls.length - 1) {
if (err.name === "AbortError") {
throw new Error("Request timed out. Both backend attempts failed.");
}
throw err;
}
throw new Error(message || `Request failed with status ${response.status}`);

console.warn(`Backend request failed at ${urls[i]}. Trying fallback...`);
} finally {
clearTimeout(timeoutId);
}
}

throw lastError || new Error("All backend servers are unavailable.");
}

export async function apiRequest(
endpoint: string,
options: RequestInit = {},
token?: string,
isMultipart: boolean = false
): Promise<Response> {
return requestWithFallback(endpoint, options, token, isMultipart);
}

export async function apiFetch<T>(
endpoint: string,
options: RequestInit = {},
token?: string,
isMultipart: boolean = false
): Promise<T> {
const response = await apiRequest(endpoint, options, token, isMultipart);

if (!response.ok) {
let message = await response.text();

return response.json();
} catch (err: any) {
if (err.name === "AbortError") {
throw new Error(`Request timed out after ${DEFAULT_TIMEOUT_MS / 1000} seconds. Please check if your backend server is running and accessible.`);
if (message.includes("<!DOCTYPE html>") || message.includes("<html>")) {
message =
response.status === 404
? `Endpoint ${endpoint} not implemented on the backend yet.`
: `Server error ${response.status}: ${response.statusText}`;
} else {
try {
const jsonError = JSON.parse(message);
message = jsonError.error || jsonError.message || message;
} catch {
// Keep the original error message.
}
}
throw err;
} finally {
clearTimeout(timeoutId);

throw new Error(message || `Request failed with status ${response.status}`);
}

return response.json();
}
31 changes: 17 additions & 14 deletions frontend/api/output.api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { apiFetch } from "./api";

import { apiFetch, apiRequest } from "./api";

export interface TranslateResponse {
translatedAiInsights: {
Expand All @@ -23,34 +24,36 @@ export async function translateInsights(
);
}

const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL || "http://localhost:5000/api";

export async function generateSpeechUri(
token: string | null,
aiInsights: any,
language: string
): Promise<string> {
const response = await fetch(`${API_BASE_URL}/output/speech`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
const response = await apiRequest(
"/output/speech",
{
method: "POST",
body: JSON.stringify({
aiInsights,
language,
speaker: "shubh",
}),
},
body: JSON.stringify({ aiInsights, language, speaker: "shubh" }), // Use valid speaker "shubh"
});
token || undefined
);

if (!response.ok) {
throw new Error("Failed to generate speech");
}

// We need to read the audio blob as base64 and return a data URI for expo-audio
const blob = await response.blob();

return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result as string); // reader.result is already a data URI string
};

reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;

reader.readAsDataURL(blob);
});
}
40 changes: 23 additions & 17 deletions frontend/api/query.api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL!;

import { apiRequest } from "./api";
import { File } from "expo-file-system";
import { Platform } from "react-native";

export interface QueryResponse {
query: string;
Expand All @@ -8,17 +11,16 @@ export interface QueryResponse {
aggregatedContext?: string;
}

import { File } from "expo-file-system";
import { Platform } from 'react-native';

export async function submitQuery(
token: string,
searchText?: string | null,
audioUri?: string | null
): Promise<QueryResponse> {
let response: Response;

if (audioUri) {
const formData = new FormData();

if (Platform.OS === "web") {
const res = await fetch(audioUri);
const blob = await res.blob();
Expand All @@ -27,25 +29,29 @@ export async function submitQuery(
const file = new File(audioUri);
formData.append("audio", file);
}
response = await fetch(`${API_BASE_URL}/query`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,

response = await apiRequest(
"/query",
{
method: "POST",
body: formData,
},
body: formData,
});
token,
true
);
} else if (searchText) {
response = await fetch(`${API_BASE_URL}/query`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
response = await apiRequest(
"/query",
{
method: "POST",
body: JSON.stringify({ query: searchText }),
},
body: JSON.stringify({ query: searchText }),
});
token
);
} else {
throw new Error("Must provide either text query or audio.");
}

if (!response.ok) {
const message = await response.text();
throw new Error(`API error: ${message}`);
Expand Down
Loading