angular-persistence
Version:
A library to handle persistence for Angular 2 applications.
105 lines • 3.69 kB
JavaScript
import { Observable } from 'rxjs';
import { StorageType } from '../constants/persistence.storage_type';
/**
* Internal class which is an implementation of the ICache interface. This is
* intended to be a private class for framework use only and will not be
* exported by the libraries modules.
*
* @export
* \@class CacheImpl
* @template T the type of value being cached
*
* @author Scott O'Bryan
* \@since 1.0
*/
export var CacheImpl = (function () {
/**
* Creates an instance of CacheImpl.
* @param {?} key
* @param {?} _loader
* @param {?} service
* @param {?=} config
*/
function CacheImpl(key, _loader, service, config) {
var _this = this;
if (config === void 0) { config = {}; }
this._loader = _loader;
var type = config.type || StorageType.MEMORY;
// For safety sake, ensure that oneUse is not present in configuration
service.defineProperty(this, "_value", key, config);
this._changes = service.changes({ key: key, type: type })
.map(function (def) { return _this._value; })
.publishBehavior(this._value)
.refCount();
}
/**
* Returns an observable to a cached value if one is loaded or
* to the value specified by the loader that was supplied when
* this cache was created if it is not.
*
* single value when it's available before marking the stream
* as complete.
* @return {?}
*/
CacheImpl.prototype.get = function () {
var _this = this;
var /** @type {?} */ result = this._value;
if (result === undefined) {
/*
* smo - if we do not have a result, then we might still have an observable from
* a previous call loaded in memory cache.
*/
var /** @type {?} */ observable = this._cachedObservable;
if (observable === undefined) {
var /** @type {?} */ loaded = this._loader();
if (loaded && loaded instanceof Observable) {
var /** @type {?} */ newObservable = ((loaded))
.publishLast()
.refCount()
.do(function (value) { return _this._value = value; })
.do(function (value) { return _this._cachedObservable = undefined; });
// cache the observable before publishing
this._cachedObservable = newObservable;
return newObservable;
}
else {
// static values simply get assigned immedietly
result = (loaded);
this._value = result;
}
}
else {
return observable;
}
}
// We have a real value so we need to make an observable that returns said value
return Observable.of(result);
};
/**
* A hot observable returning changes over time.
*
* @return {?}
*/
CacheImpl.prototype.changes = function () {
return this._changes;
};
/**
* Clears the cached value forcing a reload.
* @return {?}
*/
CacheImpl.prototype.clear = function () {
this._value = undefined;
};
return CacheImpl;
}());
function CacheImpl_tsickle_Closure_declarations() {
/** @type {?} */
CacheImpl.prototype._value;
/** @type {?} */
CacheImpl.prototype._cachedObservable;
/** @type {?} */
CacheImpl.prototype._changes;
/** @type {?} */
CacheImpl.prototype._loader;
}
//# sourceMappingURL=persistence.cache-impl.js.map