0

I want to have a cookie data determine which api I need to run. I am using react and have a separate api file. Do I add the code in the react component? Or have it in the api file?

If cookie id exist, run API, if not, make a cookie and run a post API

import Redis from 'ioredis'

let redis = new Redis(process.env.REDIS_URL)

export default async (req, res) => {
   let start = Date.now();
   let cache = await redis.get("cache")
   cache = JSON.parse(cache)
   let result = {}
   if (cache) {
       console.log("loading from cache")
       result.data = cache
       result.type = "redis"
       result.latency = Date.now() - start;
       return res.status(200).json(result)
   } else {
       console.log("loading from api")
       start = Date.now();
       return fetch('https://coronavirus-19-api.herokuapp.com/countries')
           .then(r => r.json())
           .then(data => {
               data.sort(function (a, b) {
                   return b.todayCases - a.todayCases;
               });
               result.data = data.splice(1, 11)
               result.type = "api"
               result.latency = Date.now() - start;
               redis.set("cache", JSON.stringify(result.data), "EX", 60)
               return res.status(200).json(result)
           })
   }
}
journalsup
  • 138
  • 1
  • 10
  • This code you shared is a backend express app I assume, the code to create the cookie needs to be in the backend. You can take a look here: https://stackoverflow.com/questions/16209145/how-can-i-set-cookie-in-node-js-using-express-framework But will the frontend make the check to run the API or not? Or is the backend that is going to make the check? – Paulo Fernando Jun 12 '23 at 00:08

0 Answers0