| 1 | import { NextResponse } from 'next/server'; |
| 2 | |
| 3 | /** |
| 4 | * OSIRIS — Air Quality Monitoring API |
| 5 | * Fetches real-time global air quality data from OpenAQ |
| 6 | * FREE — No API key required |
| 7 | * Data: PM2.5, PM10, O3, NO2, SO2, CO measurements worldwide |
| 8 | */ |
| 9 | |
| 10 | export async function GET() { |
| 11 | try { |
| 12 | // OpenAQ v2 — get latest measurements globally |
| 13 | // We request PM2.5 (most health-relevant) with coordinates |
| 14 | const urls = [ |
| 15 | 'https://api.openaq.org/v2/latest?limit=500¶meter=pm25&order_by=lastUpdated&sort=desc', |
| 16 | ]; |
| 17 | |
| 18 | const results = await Promise.allSettled( |
| 19 | urls.map(url => |
| 20 | fetch(url, { |
| 21 | signal: AbortSignal.timeout(10000), |
| 22 | headers: { 'Accept': 'application/json' }, |
| 23 | }).then(r => r.json()) |
| 24 | ) |
| 25 | ); |
| 26 | |
| 27 | const stations: any[] = []; |
| 28 | for (const result of results) { |
| 29 | if (result.status !== 'fulfilled') continue; |
| 30 | const data = result.value; |
| 31 | for (const loc of data.results || []) { |
| 32 | if (!loc.coordinates?.latitude || !loc.coordinates?.longitude) continue; |
| 33 | const pm25 = loc.measurements?.find((m: any) => m.parameter === 'pm25'); |
| 34 | if (!pm25) continue; |
| 35 | |
| 36 | // AQI color coding based on PM2.5 (WHO/EPA scale) |
| 37 | const val = pm25.value; |
| 38 | let level = 'Good'; |
| 39 | let color = '#00E676'; |
| 40 | if (val > 150) { level = 'Hazardous'; color = '#8B0000'; } |
| 41 | else if (val > 100) { level = 'Unhealthy'; color = '#FF1744'; } |
| 42 | else if (val > 55) { level = 'Unhealthy (Sensitive)'; color = '#FF9500'; } |
| 43 | else if (val > 35) { level = 'Moderate'; color = '#FFD700'; } |
| 44 | |
| 45 | stations.push({ |
| 46 | id: `aq-${loc.location}`, |
| 47 | name: loc.location, |
| 48 | city: loc.city || 'Unknown', |
| 49 | country: loc.country, |
| 50 | lat: loc.coordinates.latitude, |
| 51 | lng: loc.coordinates.longitude, |
| 52 | pm25: val, |
| 53 | unit: pm25.unit, |
| 54 | level, |
| 55 | color, |
| 56 | lastUpdated: pm25.lastUpdated, |
| 57 | }); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | return NextResponse.json({ |
| 62 | stations, |
| 63 | total: stations.length, |
| 64 | timestamp: new Date().toISOString(), |
| 65 | }); |
| 66 | } catch (error) { |
| 67 | console.error('Air Quality API error:', error); |
| 68 | return NextResponse.json({ stations: [], error: 'Failed to fetch air quality data' }, { status: 500 }); |
| 69 | } |
| 70 | } |