Skip to content

Instantly share code, notes, and snippets.

@saibotsivad
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saibotsivad/84d8faf3c8351c89ea3b to your computer and use it in GitHub Desktop.
Save saibotsivad/84d8faf3c8351c89ea3b to your computer and use it in GitHub Desktop.
Example Angular.js use of the simple-request-caching module
angular.module('requestFromServer', [ 'simpleRequestCaching' ]).factory('requestFromServer', function($http, simpleRequestCaching) {
return new simpleRequestCaching({
cacheMillis: 1000 * 60, // one minute cache
request: function(params) {
return $http.get('/api/data', params)
}
})
})
/*
The angularized version of: https://github.com/tobiaslabs/simple-request-caching
npm version: 0.0.7
Released under the VOL: http://veryopenlicense.com
*/
angular.module('simpleRequestCaching', []).factory('SimpleRequestCaching', function($timeout) {
function SimpleRequestCaching(options) {
if (!options || typeof options.cacheMillis !== 'number' || !options.request) {
throw new Error('SimpleRequestCaching requires the options object: {cacheMillis, request}')
}
options.stringify = options.stringify || SimpleRequestCaching.stringifyForFlatObjects
var previousRequests = {}
return function makeRequest(request) {
var requestString = options.stringify(request)
var previousRequest = previousRequests[requestString]
var promise
if (!previousRequest || SimpleRequestCaching.hasExpired(previousRequest.requested, new Date(), options.cacheMillis)) {
previousRequests[requestString] = {
requested: new Date(),
promise: options.request(request)
}
previousRequests[requestString].promise.then(function noop(){}, function errorHandler() {
delete previousRequests[requestString]
})
previousRequest = previousRequests[requestString]
if (options.cacheMillis >= 0) {
$timeout(function destroyCachedRequest() {
delete previousRequests[requestString]
}, options.cacheMillis)
}
}
return previousRequest.promise
}
}
SimpleRequestCaching.stringifyForFlatObjects = function stringifyForFlatObjects(obj) {
return JSON.stringify(Object.keys(obj).sort().reduce(function(ary, key) {
return ary.concat([key, obj[key]])
}, []))
}
SimpleRequestCaching.hasExpired = function hasExpired(previousRequestDate, now, millis) {
if (millis < 0) {
return false
} else {
var expireDate = new Date(previousRequestDate.getTime() + millis)
return expireDate.getTime() < now.getTime()
}
}
return SimpleRequestCaching
})
angular.module('someController', [ 'requestFromServer' ]).controller('SomeCtrl', function($scope, requestFromServer) {
$scope.params = {}
$scope.update = function(params) {
$scope.loading = true
requestFromServer($scope.params).then(function(data) {
$scope.loading = false
$scope.username = data.username
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment