Amnesia Cache
Really* convenient cache for $http requests that get querried in succession (shared remote config for some components). It will return the same entity as long as it's not querried for the same entity for given time. It might be a better idea to write a service for those, if you need some more custom handling / behavior. AmnesiaCache
is just convenient.
Let's say that we give our AmnesiaCache
a lifespan of 2000
(2s
).
Any entity that will have at least 2s
of pause in between, AmnesiaCache
will forget it, like so:
-
0ms
; get/foo
- query to server, returnpromise#1
, reset timer to2000ms
-
100ms
; get/foo
- returnpromise#1
, set timer to2000ms
-
1100ms
; get/foo
- returnpromise#1
, reset timer to2000ms
-
3100ms
; timeout reached - clear cache for/foo
-
3200ms
; get/foo
- query to server, returnpromise#2
, set timer to2000ms
- ...
API
AmnesiaCacheProvider
Provider for AmnesiaCache
.
-
defaultLifespan( lifespan:int )
- sets the default global lifespan (inms
) for cache.
AmnesiaCache
Cache generated with $cacheFactory
(with get( id )
proxied through timeout) , but capable of generating a custom amnesia cache with #custom( lifespan, affectGlobal )
.
-
[new] AmnesiaCache( [timespan:int] )
- constructor. Will return the same cache entity, if not initialized withnew
operator (and create a new instance, if needed). If notimespan
provided, it will use the default one.
AMD (require.js, ...)
This module uses 'angular' as a dependency, so just make sure that you have it's path set up properly.
It's wrapped like so:
define( [ 'angular' ], function ( angular ) { ... });
CommonJS (browserify, ...)
This module uses 'angular' as a dependency, so just make sure that you have it's path set up properly.
It's declaration is equivalent to:
var angular = require( 'angular' );
Sample integration
// global
angular.module( 'fooModule', [ 'str.amnesia-cache' ] )
.config(function ( AmnesiaCacheProvider ) {
AmnesiaCacheProvider.defaultLifespan( 3000 );
})
.run(function( $http, AmnesiaCache ) {
$http.defaults.cache = new AmnesiaCache();
})
// custom
angular.module( 'fooModule' )
.service('fooService', function ( $http, AmnesiaCache ) {
this.getWithDefaultAmnesia = function( url ) {
return $http.get( url, {
cache : true
});
};
this.getWithCustomAmnesia = function( url ) {
return $http.get( url, {
cache : new AmnesiaCache( 1000 )
});
};
});