88 lines
2.7 KiB
JavaScript
88 lines
2.7 KiB
JavaScript
const express = require('express');
|
|
const axios = require('axios');
|
|
|
|
const app = express();
|
|
const PORT = 3000;
|
|
|
|
app.use(express.static('public'));
|
|
|
|
// Функция для парсинга CSV-ответа от IEM API
|
|
function parseIEMData(csvData) {
|
|
const lines = csvData.trim().split('\n');
|
|
if (lines.length < 2) {
|
|
return [];
|
|
}
|
|
|
|
const headerLine = lines.find(line => !line.startsWith('#'));
|
|
if (!headerLine) return [];
|
|
|
|
const headers = headerLine.split(',');
|
|
|
|
const dataLines = lines.filter(line => !line.startsWith('#') && line !== headerLine);
|
|
|
|
const jsonData = dataLines.map(line => {
|
|
const values = line.split(',');
|
|
const report = {};
|
|
headers.forEach((header, index) => {
|
|
const value = values[index];
|
|
const numValue = (value === 'M' || value === '') ? null : parseFloat(value);
|
|
if (['tmpf', 'dwpf', 'alti', 'sknt', 'drct'].includes(header)) {
|
|
report[header] = numValue;
|
|
} else {
|
|
report[header] = values[index];
|
|
}
|
|
});
|
|
return report;
|
|
});
|
|
|
|
return jsonData;
|
|
}
|
|
|
|
|
|
app.get('/api/metar', async (req, res) => {
|
|
const { station, days } = req.query;
|
|
|
|
if (!station) {
|
|
return res.status(400).json({ error: 'Station code is required' });
|
|
}
|
|
|
|
const endDate = new Date();
|
|
const startDate = new Date();
|
|
startDate.setDate(endDate.getDate() - parseInt(days, 10));
|
|
|
|
const iemApiUrl = `https://mesonet.agron.iastate.edu/cgi-bin/request/asos.py?` +
|
|
`station=${station}&` +
|
|
`data=metar&` +
|
|
`data=tmpf&` +
|
|
`data=dwpf&` +
|
|
`data=alti&` +
|
|
`data=sknt&` +
|
|
`data=drct&` +
|
|
`year1=${startDate.getUTCFullYear()}&month1=${startDate.getUTCMonth() + 1}&day1=${startDate.getUTCDate()}&` +
|
|
`year2=${endDate.getUTCFullYear()}&month2=${endDate.getUTCMonth() + 1}&day2=${endDate.getUTCDate()}&` +
|
|
`tz=Etc/UTC&` +
|
|
`format=comma&` +
|
|
`latlon=no&` +
|
|
`missing=M`;
|
|
|
|
try {
|
|
console.log(`Fetching data from: ${iemApiUrl}`);
|
|
const response = await axios.get(iemApiUrl);
|
|
|
|
if (!response.data || response.data.trim() === '' || response.data.includes('No data found')) {
|
|
return res.status(404).json({ error: 'No data found for the specified station or period.' });
|
|
}
|
|
|
|
const jsonData = parseIEMData(response.data);
|
|
|
|
res.json({ data: jsonData });
|
|
|
|
} catch (error) {
|
|
console.error('Error fetching data from IEM API:', error.message);
|
|
res.status(500).json({ error: 'Failed to fetch or process data from IEM API.' });
|
|
}
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server is running on http://localhost:${PORT}`);
|
|
}); |