Learn by Directing AI
All materials

api.js

jsapi.js
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';

export async function fetchTreks() {
  const res = await fetch(`${API_URL}/api/treks`);
  if (!res.ok) throw new Error('Failed to fetch treks');
  return res.json();
}

export async function fetchTrek(id) {
  const res = await fetch(`${API_URL}/api/treks/${id}`);
  if (!res.ok) throw new Error('Failed to fetch trek');
  return res.json();
}

export async function createBooking(data) {
  const res = await fetch(`${API_URL}/api/bookings`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  if (!res.ok) {
    const err = await res.json();
    throw new Error(err.error || 'Failed to create booking');
  }
  return res.json();
}

export async function fetchBookings(email) {
  const url = email
    ? `${API_URL}/api/bookings?customer_email=${encodeURIComponent(email)}`
    : `${API_URL}/api/bookings`;
  const res = await fetch(url);
  if (!res.ok) throw new Error('Failed to fetch bookings');
  return res.json();
}