Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
2.1 kB
4
Indexable
Never
import { cookies } from "next/headers";

const myCookie = cookies()
  .getAll()
  .map(c => c.name + "=" + c.value)
  .join("; ");

type Endpoints = "getAllRooms" | "getAvailableRooms" | "getTemporaryHold";
interface FetchDataResponse {
  getAllRooms?: any;
  getAvailableRooms?: any;
  getTemporaryHold?: any;
}

const endpoints: Record<Endpoints, { url: string }> = {
  getAllRooms: {
    url: `${process.env.NEXT_PUBLIC_SERVER_URL}/room/all?paginate=false`
  },
  getAvailableRooms: {
    url: `${process.env.NEXT_PUBLIC_SERVER_URL}/rooms?paginate=false&startDate=${new Date(
      new Date(new Date()).setUTCHours(0, 0, 0, 0)
    ).toISOString()}`
  },
  getTemporaryHold: {
    url: `${process.env.NEXT_PUBLIC_SERVER_URL}/booking/temp/hold?date=2024-07-08T00:00:00.000Z&from=server`
  }
};

const fetchDataBooking = async (fetchSpecific: Endpoints[] = []): Promise<FetchDataResponse> => {
  try {
    const keysToFetch = fetchSpecific.length > 0 ? fetchSpecific : (Object.keys(endpoints) as Endpoints[]);
    const fetchPromises = keysToFetch.map(key =>
      fetch(endpoints[key].url, {
        method: "GET",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          Cookie: myCookie
        },
        cache: "no-store"
      })
    );
    const responses = await Promise.all(fetchPromises);
    responses.forEach(response => {
      if (!response.ok) {
        throw new Error(`Failed to fetch data from ${response.url}: ${response.statusText}`);
      }
    });
    const jsonData = await Promise.all(responses.map(response => response.json()));

    const fetchedData: FetchDataResponse = keysToFetch.reduce((acc, key, index) => {
      acc[key] = jsonData[index];
      return acc;
    }, {} as FetchDataResponse);
    return fetchedData;
  } catch (error) {
    console.error("Error fetching data:", error);
    return {
      getAllRooms: [],
      getAvailableRooms: [],
      getTemporaryHold: []
    };
  }
};

export default fetchDataBooking;
Leave a Comment