0

I have an endpoint in express.

app.get('/',(req,res)=>{

   Promise.all(fetch(url1),fetch(url2))
      .then(i=>res.send(i=))
})

I'd like to make a cache to avoid to make the requests only every 15seconds. Let's says it take 5 seconds to make both fetch.

If I do a simple cache like this:

    const cache={};

    app.get('/',(req,res)=>{
        if(cache['mykey']==undefined 
           || cache['mykey'].timestamp>new Date().getTime()-15000){
// make or refresh cache;
            Promise.all(fetch(url1),fetch(url2))
                .then(i=>{
                    cache['mykey'].timestamp=new Date().getTime();
                    cache['mykey'].value=i
                    return i;
                })
                .then(i=>res.send(i))
        }else{
            res.send(cache['mykey'].value);
            // or res.status(304).send()
        }
    }

It will not work if 2 or more request are made during the phase of cache refreshing. How can I make only ONE cache refreshing every 15 minutes ?

Hope I am clear.

Stefdelec
  • 2,711
  • 3
  • 33
  • 40

1 Answers1

1

This is an outline, not tested:

let cache = false

app.get('/', function(req, res) {
    cache = cache || Promise.all([
        fetch('url1'),
        fetch('url2')
    ]).then(results => {
        setTimeout(() => cache = false, 15 * 1000);
        return results;
    });

    const result = cache 

    result.then(([result1, result2]) => {
        res.json({ result1, result2 });
    });
});
Teneff
  • 30,564
  • 13
  • 72
  • 103
  • Depending on the requirements, you'll likely also want to void the cache in case an error happens. Maybe just use `finally` instead of `then`. – Bergi Sep 20 '18 at 15:00
  • I don't really understand the code. If 2 requests arrive during cache refreshing, they'll both 'fetch' the url. Or will it be only one fetching (one for url1 and one for url2)? – Stefdelec Sep 21 '18 at 06:09