Lee
Lee

Reputation: 45

Node/Express app to query a 3rd party API and store response in memcache/redis for 30 mins for future queries

General query here in terms of app structure. Basically I have an SPA that I aim to display odds from a 3rd party API.

In order to reduce the workload on that API I'd like to build a node/express middleware so that queries are first checking a memcache/redis cache and if cached, and same value, return the data, if not cached then hit the API and return the response whilst adding to the cache for future queries for a time limit of X. (not sure if I'd need an actual db like mongodb to work with the cache)

The key part here I'd like to achieve is the caching as I want to avoid the API having to respond if the data is the same, hence the cache.

I guess my question here is does the above scenario make sense or am I over complicating it before even starting?

Apologies for any errors , Back-end and caching is very new to me.

Thanks in advance

Upvotes: 2

Views: 1135

Answers (1)

shamon shamsudeen
shamon shamsudeen

Reputation: 5848

The idea is to first to check the data is in the cache if not then fetch from API and write to cache.

Here is sample implementation with redis and request

function getThirdParty(req,res){

    //unique identifier for the cache 
    const redisKey = req.body.key 

    //check the result is in cache
    client.getAsync(redisKey).then(function(result) {
       if(result){ 
           res.json({
               result:result,
               cache:true
           })
     }else{
        //not in cache made the api request 
        request('http://www.thirdpartyapi.com', function (error, response, body) {
        //set the api  result in cache   
        client.set(redisKey,body);

            res.json({
                result:body,
                cache:false
            })
     });
    }
 });
 }

Upvotes: 3

Related Questions