DocsπŸ“± AppπŸ“š API Reference

API Reference

Supabase Services

HealthProfileService

Manages user health data, metrics, and goal calculations.

getHealthProfile(userId: string)

Fetches the health profile for a given user.

Parameters:

  • userId (string) - The user’s unique identifier

Returns:

Promise<{
  id: string;
  user_id: string;
  height: number;
  weight: number;
  goal_weight: number;
  age: number;
  gender: 'male' | 'female' | 'other';
  activity_level: string;
  dietary_preference: string;
  daily_calorie_target: number;
  created_at: string;
  updated_at: string;
}>

Example:

const profile = await HealthProfileService.getHealthProfile(userId);
console.log(profile.daily_calorie_target);

updateHealthProfile(userId: string, data: object)

Updates health metrics for a user.

Parameters:

  • userId (string) - The user’s unique identifier
  • data (object) - Key-value pairs to update

Returns:

Promise<{ success: boolean; data?: object; error?: string }>

Example:

await HealthProfileService.updateHealthProfile(userId, {
  weight: 75,
  goal_weight: 70
});

calculateDailyCalories(profile: HealthProfile)

Calculates recommended daily calorie intake based on user profile.

Parameters:

  • profile (HealthProfile) - User’s health profile object

Returns:

{
  bmr: number;              // Basal Metabolic Rate
  tdee: number;             // Total Daily Energy Expenditure
  target: number;           // Daily calorie target
  deficit: number;          // Calorie deficit for weight loss
}

UserEntriesService

Handles food and workout entry operations.

addFoodEntry(userId: string, entry: FoodEntry)

Logs a food entry to the database.

Parameters:

  • userId (string) - The user’s unique identifier
  • entry (FoodEntry) - Food entry details

FoodEntry Type:

{
  food_name: string;
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
  serving_size?: string;
  meal_type?: 'breakfast' | 'lunch' | 'dinner' | 'snack';
  photo_url?: string;
  notes?: string;
}

Returns:

Promise<{ id: string; created_at: string }>

addWorkoutEntry(userId: string, entry: WorkoutEntry)

Logs a workout entry to the database.

Parameters:

  • userId (string) - The user’s unique identifier
  • entry (WorkoutEntry) - Workout entry details

WorkoutEntry Type:

{
  exercise_name: string;
  duration_minutes: number;
  calories_burned: number;
  exercise_type?: 'cardio' | 'strength' | 'flexibility' | 'sports';
  intensity?: 'low' | 'medium' | 'high';
  notes?: string;
  photo_url?: string;
}

Returns:

Promise<{ id: string; created_at: string }>

getEntriesByDate(userId: string, date: string)

Fetches all entries for a specific date.

Parameters:

  • userId (string) - The user’s unique identifier
  • date (string) - Date in ISO format (YYYY-MM-DD)

Returns:

Promise<{
  foodEntries: FoodEntry[];
  workoutEntries: WorkoutEntry[];
  totalCaloriesConsumed: number;
  totalCaloriesBurned: number;
  netCalories: number;
}>

deleteEntry(entryId: string, type: 'food' | 'workout')

Removes an entry from the database.

Parameters:

  • entryId (string) - The entry’s unique identifier
  • type (β€˜food’ | β€˜workout’) - Type of entry to delete

Returns:

Promise<{ success: boolean }>

FoodAnalysisService

AI-powered food recognition and nutritional analysis.

analyzeFood(imageUri: string)

Analyzes a food photo using OpenAI Vision API.

Parameters:

  • imageUri (string) - Local file URI of the food image

Returns:

Promise<{
  foods: Array<{
    name: string;
    serving_size: string;
    calories: number;
    protein: number;
    carbs: number;
    fat: number;
    fiber?: number;
    sugar?: number;
  }>;
  total_calories: number;
  confidence: number;
}>

Example:

const result = await FoodAnalysisService.analyzeFood(photoUri);
console.log(`Total calories: ${result.total_calories}`);

getNutritionalData(foodName: string)

Looks up nutritional information from the database.

Parameters:

  • foodName (string) - Name of the food item

Returns:

Promise<{
  name: string;
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
  serving_size: string;
  // ... additional nutrients
}>

WorkoutAnalysisService

AI-powered workout recognition and calorie burn estimation.

analyzeWorkout(imageUri: string)

Recognizes exercise type from a photo.

Parameters:

  • imageUri (string) - Local file URI of the workout image

Returns:

Promise<{
  exercise_name: string;
  exercise_type: 'cardio' | 'strength' | 'flexibility';
  estimated_duration?: number;
  confidence: number;
}>

calculateCaloriesBurned(exercise: string, duration: number, weight: number)

Estimates calories burned during exercise.

Parameters:

  • exercise (string) - Exercise name
  • duration (number) - Duration in minutes
  • weight (number) - User’s weight in kg

Returns:

{
  calories_burned: number;
  met_value: number;
  intensity: 'low' | 'medium' | 'high';
}

Formula:

Calories = (MET Γ— weight_kg Γ— duration_hours)

SubscriptionService

Manages subscription status and usage tracking.

checkSubscriptionStatus(userId: string)

Verifies if user has active premium subscription.

Parameters:

  • userId (string) - The user’s unique identifier

Returns:

Promise<{
  is_premium: boolean;
  subscription_status: 'active' | 'expired' | 'canceled' | 'free';
  expires_at?: string;
  plan_type?: 'monthly' | 'yearly';
}>

getUsageStats(userId: string)

Retrieves API usage statistics for the current month.

Parameters:

  • userId (string) - The user’s unique identifier

Returns:

Promise<{
  ai_requests_used: number;
  ai_requests_limit: number;
  percentage_used: number;
  resets_at: string;
}>

upgradeSubscription(userId: string, plan: 'monthly' | 'yearly')

Initiates premium subscription purchase.

Parameters:

  • userId (string) - The user’s unique identifier
  • plan (β€˜monthly’ | β€˜yearly’) - Selected subscription plan

Returns:

Promise<{
  checkout_url: string;
  session_id: string;
}>

Database Schema

users table

CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  full_name TEXT,
  avatar_url TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

health_profiles table

CREATE TABLE health_profiles (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  height DECIMAL,
  weight DECIMAL,
  goal_weight DECIMAL,
  age INTEGER,
  gender TEXT,
  activity_level TEXT,
  dietary_preference TEXT,
  daily_calorie_target INTEGER,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

food_entries table

CREATE TABLE food_entries (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  food_name TEXT NOT NULL,
  calories INTEGER,
  protein DECIMAL,
  carbs DECIMAL,
  fat DECIMAL,
  serving_size TEXT,
  meal_type TEXT,
  photo_url TEXT,
  notes TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

workout_entries table

CREATE TABLE workout_entries (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  exercise_name TEXT NOT NULL,
  duration_minutes INTEGER,
  calories_burned INTEGER,
  exercise_type TEXT,
  intensity TEXT,
  photo_url TEXT,
  notes TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

subscriptions table

CREATE TABLE subscriptions (
  id UUID PRIMARY KEY,
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  status TEXT NOT NULL,
  plan_type TEXT,
  stripe_subscription_id TEXT,
  current_period_start TIMESTAMP,
  current_period_end TIMESTAMP,
  ai_requests_used INTEGER DEFAULT 0,
  ai_requests_limit INTEGER DEFAULT 50,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

Error Handling

All service methods throw errors that should be caught:

try {
  const result = await FoodAnalysisService.analyzeFood(imageUri);
  // Handle success
} catch (error) {
  if (error.code === 'RATE_LIMIT_EXCEEDED') {
    // Show upgrade prompt
  } else if (error.code === 'NETWORK_ERROR') {
    // Show retry option
  } else {
    // Generic error handling
  }
}

Common Error Codes

  • RATE_LIMIT_EXCEEDED - AI request limit reached
  • NETWORK_ERROR - Connection failed
  • AUTH_ERROR - Authentication failed
  • NOT_FOUND - Resource not found
  • VALIDATION_ERROR - Invalid input data
  • SERVER_ERROR - Internal server error