$http simultaneous duplicate API call, return promise

426 Views Asked by At

In my app, we are using micro services structure, and for that we have aso added caching.

But there is a scenario in which multiple same request gets fired, and the request are fired at the same time, so caching also doesn't seem to work. I want that for duplicate request it should send promise of previous request.

Also there are lots of services, so adding promise to each service will not work. Is there any place where to handle duplicate request and pass the previous request promise at a common place. might be by using decorator or http interceptor.

Service call

testService.getTestByIds = function (
                                testIds,
                                contextInfo) {
         var params = {
                 testId: requestDefinitionIds
           };
         params = CommonProvider.apppendContextParams(contextInfo, params,testInfoCache);
          return $http.get(SERVICE_URL + 'tests', {
                                cache: testInfoCache,
                                params: params,
                                transformResponse: CommonProvider.appendTransformer($http.defaults.transformResponse, function (value) {
                                    return transformTestResponse(value);
                                })
                            });
                        };
1

There are 1 best solutions below

2
HMR On

I assume you mean caching on the client, you could try something like this:

const activeRequest = 
  () => {
    const requests = {};
    return (url,params) => {
      const promise = requests[url+JSON.stringify(params)];
      if(promise){
        return promise;
      }
      return requests[url+JSON.stringify(params)] = 
        //not sure what you use for angular, maybe $http for angular1
        fetch(url,params)
        .then(
          x=>{
            requests[url+JSON.stringify(params)] = undefined;
            return x;
          }
        )
    }
  }