Cache league table
Cache the league table for 12 hours in redis
This commit is contained in:
parent
031a597fb7
commit
beb1ccb2ec
36
index.js
36
index.js
@ -3,6 +3,12 @@ const axios = require('axios');
|
|||||||
const redis = require('redis');
|
const redis = require('redis');
|
||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
const app = express();
|
const app = express();
|
||||||
|
const redisPort = 6379;
|
||||||
|
const client = redis.createClient(redisPort);
|
||||||
|
|
||||||
|
client.on('error', (err) => {
|
||||||
|
console.log(err);
|
||||||
|
});
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
headers: {
|
headers: {
|
||||||
@ -16,13 +22,31 @@ const config = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
app.get('/pl', async (req, res) => {
|
app.get('/pl', async (req, res) => {
|
||||||
|
const league = '39';
|
||||||
try {
|
try {
|
||||||
const leagueTable = await axios.get(
|
client.get(league, async (err, leagueTable) => {
|
||||||
'https://v3.football.api-sports.io/standings',
|
if (err) throw err;
|
||||||
config
|
|
||||||
);
|
// Return cached league table if present
|
||||||
res.status(200).send({
|
if (leagueTable) {
|
||||||
table: leagueTable.data,
|
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',
|
||||||
|
config
|
||||||
|
);
|
||||||
|
// 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) {
|
} catch (err) {
|
||||||
res.status(500).send({ message: err.message });
|
res.status(500).send({ message: err.message });
|
||||||
|
Loading…
x
Reference in New Issue
Block a user