|
| 1 | +const express = require('express'); |
| 2 | +const got = require('got'); |
| 3 | +const WEATHER_API_URL = 'https://node-congress.workshop.epsagon.com/weather'; |
| 4 | +const NEWS_API_URL = 'https://node-congress.workshop.epsagon.com/news'; |
| 5 | +const FACT_API_URL = 'https://node-congress.workshop.epsagon.com/fact'; |
| 6 | + |
| 7 | + |
| 8 | +function getWeather(city = '') { |
| 9 | + const URL = `${WEATHER_API_URL}/${city}` |
| 10 | + return got(URL).json().catch((err) => null); // json |
| 11 | +} |
| 12 | +function getNews(city = '') { |
| 13 | + const URL = `${NEWS_API_URL}/${city}` |
| 14 | + return got(URL).json().catch((err) => null); // json |
| 15 | +} |
| 16 | +function getFactForToday() { |
| 17 | + const d = new Date(); |
| 18 | + const month = d.getMonth() + 1; |
| 19 | + const day = d.getDate(); |
| 20 | + const URL = `${FACT_API_URL}/${month}/${day}`; |
| 21 | + return got(URL).text().catch((err) => null); // string |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +const app = express(); |
| 26 | +app.get('/digest/:city', async (req, res) => { |
| 27 | + const city = req.params.city; |
| 28 | + const [weather, news, fact] = await Promise.all([ |
| 29 | + getWeather(city), |
| 30 | + getNews(city), |
| 31 | + getFactForToday() |
| 32 | + ]); |
| 33 | + res.json({ weather, news, fact }); |
| 34 | +}); |
| 35 | +app.use('*', (req, res) => { |
| 36 | + res.status(404).send('Not Found'); |
| 37 | +}) |
| 38 | +app.listen(3000, () => console.log('App is now online at port 3000')); |
| 39 | + |
| 40 | + |
| 41 | + |
0 commit comments