| 1 | /// <reference path="../pb_data/types.d.ts" /> |
| 2 | |
| 3 | routerAdd("GET", " |
| 4 | |
| 5 | if (!c.auth |
| 6 | // Get query parameters |
| 7 | const from = |
| 8 | const to = |
| 9 | const date = |
| 10 | const apiKey = |
| 11 | |
| 12 | // Validate required parameters |
| 13 | if (!from || |
| 14 | return c.json |
| 15 | success: false, |
| 16 | message: "Missing required parameters: from, to, and date are required", |
| 17 | }); |
| 18 | } |
| 19 | |
| 20 | const _date = |
| 21 | const dayEndDate = |
| 22 | dayEndDate.setDate(_date |
| 23 | try { |
| 24 | /** |
| 25 | * && date >= "${_date |
| 26 | .toISOString() |
| 27 | .replace("T", " ") |
| 28 | .replace(".000Z", "")}" && date <= "${dayEndDate |
| 29 | .toISOString() |
| 30 | .replace("T", " ") |
| 31 | .replace(".000Z", "")}" |
| 32 | |
| 33 | append this to filter before going to production. I used without this to not exceed my API quota |
| 34 | */ |
| 35 | const records = |
| 36 | "flights", |
| 37 | `arrival.iataCode = "${to}" && departure.iataCode = "${ |
| 38 | "-created", |
| 39 | 200, |
| 40 | 0 |
| 41 | ); |
| 42 | if (records.length |
| 43 | console.log("Fetched from db |
| 44 | return c.json |
| 45 | } |
| 46 | } catch (e) |
| 47 | console.error(e |
| 48 | } |
| 49 | try { |
| 50 | // Aviation Edge API endpoint for flight schedules |
| 51 | const apiUrl = |
| 52 | |
| 53 | // Make API request |
| 54 | const response = |
| 55 | method: "GET", |
| 56 | url: apiUrl, |
| 57 | }); |
| 58 | |
| 59 | // Check if request was successful |
| 60 | if (response.statusCode |
| 61 | console.log(response |
| 62 | throw new Error( |
| 63 | } |
| 64 | |
| 65 | // Parse response |
| 66 | const flights = |
| 67 | let collection = |
| 68 | for (const flight |
| 69 | let record = |
| 70 | record.set("date |
| 71 | record.set("airline |
| 72 | record.set("arrival |
| 73 | record.set("codeshared |
| 74 | record.set("flight |
| 75 | record.set("departure |
| 76 | record.set("type |
| 77 | record.set("status |
| 78 | $app.save(record |
| 79 | } |
| 80 | |
| 81 | // Filter flights for the specific route |
| 82 | const routeFlights = |
| 83 | (flight) => |
| 84 | flight.departure?.iataCode |
| 85 | ); |
| 86 | |
| 87 | c.response.header |
| 88 | |
| 89 | return c.json |
| 90 | success: true, |
| 91 | date: date, |
| 92 | route: { |
| 93 | from: from, |
| 94 | to: to, |
| 95 | }, |
| 96 | flightCount: routeFlights.length, |
| 97 | flights: routeFlights, |
| 98 | }); |
| 99 | } catch (error) |
| 100 | console.error("Error fetching flights: |
| 101 | |
| 102 | // Return error response |
| 103 | return c.json |
| 104 | success: false, |
| 105 | message: "Failed to fetch flight data", |
| 106 | error: error.message |
| 107 | }); |
| 108 | } |
| 109 | }); |
| 110 | |
| 111 | // Add options route for CORS |
| 112 | routerAdd("OPTIONS", " |
| 113 | c.response.header |
| 114 | c.response.header |
| 115 | c.response.header |
| 116 | c.response.header |
| 117 | return c.json |
| 118 | }); |