diff --git a/index.js b/index.js index d824db7..3cd362e 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,7 @@ client.on('error', (err) => { console.log(err); }); -const config = { +const premierLeague = { headers: { 'x-rapidapi-host': process.env.API_HOST, 'x-rapidapi-key': process.env.API_KEY, @@ -21,6 +21,17 @@ const config = { }, }; +const championship = { + headers: { + 'x-rapidapi-host': process.env.API_HOST, + 'x-rapidapi-key': process.env.API_KEY, + }, + params: { + league: '40', + season: '2020', + }, +}; + app.get('/pl', async (req, res) => { const league = '39'; try { @@ -37,7 +48,39 @@ app.get('/pl', async (req, res) => { // Fetch from the API const leagueTable = await axios.get( 'https://v3.football.api-sports.io/standings', - config + premierLeague + ); + // Save result to cache + client.setex(league, 43200, JSON.stringify(leagueTable.data)); + // Return data from API + res.status(200).send({ + table: leagueTable.data, + message: 'cache miss', + }); + } + }); + } catch (err) { + res.status(500).send({ message: err.message }); + } +}); + +app.get('/championship', async (req, res) => { + const league = '40'; + try { + client.get(league, async (err, leagueTable) => { + if (err) throw err; + + // Return cached league table if present + if (leagueTable) { + res.status(200).send({ + table: JSON.parse(leagueTable), + message: 'data retrieved from cache', + }); + } else { + // Fetch from the API + const leagueTable = await axios.get( + 'https://v3.football.api-sports.io/standings', + championship ); // Save result to cache client.setex(league, 43200, JSON.stringify(leagueTable.data));