Created
June 4, 2015 02:12
-
-
Save stephencroberts/db11532d9d313b7d3609 to your computer and use it in GitHub Desktop.
Angular service promise caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getResponse = (method, type, params) => | |
@promises ||= {} | |
promiseKey = (method + type + JSON.stringify params).replace(/[\{\}",:\-\._\[\] ]/g, '') | |
return @promises[promiseKey] if @promises[promiseKey] | |
console.log promiseKey | |
deferred = $q.defer() | |
params ||= {} | |
params.access_token = contentfulConfig.access_token | |
url = "#{contentfulConfig.protocol}://#{contentfulConfig.host}/spaces/#{contentfulConfig.space}" | |
url += "/#{type}" if type | |
query = [] | |
for key of params | |
query.push("#{key}=#{params[key]}") if params.hasOwnProperty(key) | |
url += "?#{query.join('&')}" if query.length>0 | |
$http({ | |
method: method, | |
url: url | |
}) | |
.then( | |
(response) -> | |
deferred.resolve processResponse(response.data) | |
(error) -> | |
deferred.reject error | |
) | |
.finally => delete @promises[promiseKey] | |
@promises[promiseKey] = deferred.promise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment