mirror of
https://github.com/pawelmalak/flame.git
synced 2026-02-28 01:13:11 +08:00
Created Cron job to get data from external api every 15 minutes and save it to local database. Created Weather model and controller to get latest weather status
This commit is contained in:
42
utils/getExternalWeather.js
Normal file
42
utils/getExternalWeather.js
Normal file
@@ -0,0 +1,42 @@
|
||||
const Config = require('../models/Config');
|
||||
const Weather = require('../models/Weather');
|
||||
const axios = require('axios');
|
||||
|
||||
const getExternalWeather = async () => {
|
||||
// Get API key from database
|
||||
let secret = await Config.findOne({
|
||||
where: { key: 'WEATHER_API_KEY' }
|
||||
});
|
||||
|
||||
if (!secret) {
|
||||
console.log('API key was not found');
|
||||
return;
|
||||
}
|
||||
|
||||
secret = secret.value;
|
||||
|
||||
// Fetch data from external API
|
||||
try {
|
||||
const res = await axios.get(`http://api.weatherapi.com/v1/current.json?key=${secret}&q=52.229676,21.012229`);
|
||||
|
||||
// For dev
|
||||
// console.log(res.data);
|
||||
|
||||
// Save weather data
|
||||
const cursor = res.data.current;
|
||||
await Weather.create({
|
||||
externalLastUpdate: cursor.last_updated,
|
||||
tempC: cursor.temp_c,
|
||||
tempF: cursor.temp_f,
|
||||
isDay: cursor.is_day,
|
||||
conditionText: cursor.condition.text,
|
||||
conditionCode: cursor.condition.code
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
console.log('External API request failed');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = getExternalWeather;
|
||||
11
utils/jobs.js
Normal file
11
utils/jobs.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const schedule = require('node-schedule');
|
||||
const getExternalWeather = require('./getExternalWeather');
|
||||
|
||||
const weatherJob = schedule.scheduleJob('updateWeather', '0 */15 * * * *', async () => {
|
||||
try {
|
||||
await getExternalWeather();
|
||||
console.log('weather updated');
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user