1export const getFlights = async (startDate: string, endDate: string, origin: string, destination: string) => {
2 const url = `https://booking-com15.p.rapidapi.com/api/v1/flights/searchFlights?fromId=${origin}&toId=${destination}&departDate=${startDate}&returnDate=${endDate}&pageNo=1&adults=1&sort=BEST&cabinClass=ECONOMY¤cy_code=USD`;
3 const options = {
4 method: 'GET',
5 headers: {
6 'x-rapidapi-key': process.env.RAPID_API_KEY || '',
7 'x-rapidapi-host': 'booking-com15.p.rapidapi.com',
8 },
9 };
10
11 try {
12 const response = await fetch(url, options);
13 const result = await response.json();
14
15 return result?.data?.flightOffers.map(
16 (flight: FlightApiResponse): Flight => ({
17 airline: flight.segments[0].legs[0].carriersData[0].name,
18 flightNumber: `${flight.segments[0].legs[0].flightInfo.carrierInfo.marketingCarrier}${flight.segments[0].legs[0].flightInfo.flightNumber}`,
19 departureAirport: flight.segments[0].departureAirport.code,
20 departureCity: flight.segments[0].departureAirport.cityName,
21 departureTime: new Date(flight.segments[0].departureTime),
22 arrivalAirport: flight.segments[0].arrivalAirport.code,
23 arrivalCity: flight.segments[0].arrivalAirport.cityName,
24 arrivalTime: new Date(flight.segments[0].arrivalTime),
25 duration: `${Math.floor(flight.segments[0].totalTime / 60)}h ${flight.segments[0].totalTime % 60}m`,
26 price: flight.priceBreakdown.total.units + flight.priceBreakdown.total.nanos / 1000000000,
27 }),
28 );
29 } catch (error) {
30 console.error(error);
31 }
32};