2014-09-18 1 views
0

내 응용 프로그램의 의미를 알아야하기 때문에 자체 캐시를 구현하고 있습니다. REST 서비스에 액세스하는 클라이언트 API 내에 캐시를 구현하고 있습니다. 논리는 간단합니다 : 먼저 객체의 사전을 살펴보고 요청한 객체가 없으면 네트워크를 사용하여 REST 서비스에서 객체를 요청합니다. 클라이언트 API를 사용하는 코드는 요청한 객체가 내 캐시에 있더라도 약속을 기대합니다. 내 질문입니다 : 캐시에있는 개체에 대한 약속/지연 패턴을 구현하는 가장 좋은 방법은 무엇입니까? 지금은 그것을하기 위해 타임 아웃 함수를 사용하고 있습니다. 제한 시간 함수가 충분히 좋은가? API의 사용자가 promise 객체를받은 후 제한 시간 함수가 실행된다는 보장은 무엇입니까? 내 질문의 세부 사항을 조사하려면, 아래의 코드를 참조하십시오 표시하는 코드를 단순화

만 어떤 질문에 관련 : 당신이 뭘 하려는지와

angular.module("myApp").factory("restClient", function($q, $http, $timeout, cache){ 

    var get_content=function(link){ 
     var deferred=$q.defer(); 
     $http.get(link) 
     .success(function (data) { 
      deferred.resolve(data); 
      deferred=null; 
     }) 
     .error(function (error) { 
      deferred.reject(error); 
      deferred=null; 
     }); 

     return deferred.promise; 
    }; 

return{ 

     getObject : function(objectId) { 
      //If object is in the cache 
      if (cache.contains(objectId)){ 

      var deferred=$q.defer(); 
      $timeout(function(){ 

        var objectContent=cache.get(objectId); 
        deferred.resolve(objectContent); 
        deferred=null; 

      }); 
      return deferred.promise; 


      } 
      else{ 

      //Create link 
      //return promise 
      return get_content(link); 
     } 
    } 
}); 
+0

어디에서 캐시에 넣고 있습니까? – PSL

+0

나는 클라이언트에서 바로 여기 캐시에 넣어야하지만, 그 알고리즘의 세부 사항은 건너 뛴다. –

+0

의견을 남기셨습니까? – PSL

답변

1

, 하나 개 중요한 것은 약속을 반환하는 객체가 이미있을 때 중복 지연 프로 미스 객체를 만들지 말아야합니다 (예 : $http$timeout). 다음과 같이 할 수 있습니다 : -

var get_content=function(link){ 
     return $http.get(link) 
     .then(function (response) { 
      cache.put(link, response.data); 
      return response.data; 
     }, function(response){ 
      return $q.reject(response.data); 
     }); 

    }; 

return { 

     getObject : function(objectId) { 
      //If object is in the cache 
      if (cache.contains(objectId)){ 
      return $q.when(cache.get(objectId)) 
      } 
      return get_content(objectId); 
     } 

데이터를 캐시에 저장하는 대신 캐시에 약속을 넣을 수 있습니다.

getObject : function(objectId) { 
    if (cache.contains(objectId)){ 
     return cache.get(objectId); 
    } 

    var promise = $http.get(objectId) 
     .then(function (response) { 
      //Incase you have any condition to look at the response and decide if this is a failure then invalidate it here form the cache. 
      return response.data; 
     }, function(response){ 
      cache.remove(objectId); //Remove it 
      return $q.reject("Rejection reason"); 
     }); 
     } 
     cache.put(objectId, promise); 
    return promise; 
+0

대단 했어. 정말 고마워! –

+0

@ASDF 당신은 환영합니다 .. :) – PSL

+0

@ASDF 왜 한가지 기본 캐시를 사용할 수 없습니까? 캐시를 설정하여 요청을 얻으려면 true이고, URL 만 다른가? – PSL