angularfire2-offline
Version:
Cache angularfire2 data for offline use.
86 lines (85 loc) • 3 kB
JavaScript
import { Inject, Injectable, Optional, SkipSelf } from '@angular/core';
import { LocalForageToken } from './localforage';
var LocalUpdateService = (function () {
function LocalUpdateService(localForage) {
this.localForage = localForage;
this.cache = {};
this.queue = {};
}
LocalUpdateService.prototype.update = function (key, valueFunction) {
var _this = this;
return new Promise(function (resolve) {
if (!(key in _this.queue)) {
_this.queue[key] = {
running: false,
updates: [],
};
}
_this.queue[key].updates.push({
function: valueFunction,
resolve: resolve
});
if (!_this.queue[key].running) {
_this.queue[key].running = true;
_this.updateNext(key);
}
});
};
LocalUpdateService.prototype.updateNext = function (key) {
var _this = this;
if (this.queue[key].updates.length === 0) {
this.queue[key].running = false;
return;
}
var nextUpdate = this.queue[key].updates.pop();
return new Promise(function (resolve) { return _this.checkCache(key)
.then(function () { return _this.updateValue(key, nextUpdate)
.then(function () { return _this.updateNext(key); }); }); });
};
LocalUpdateService.prototype.checkCache = function (key) {
var _this = this;
return new Promise(function (resolve) {
if (key in _this.cache) {
resolve();
}
else {
_this.localForage.getItem(key).then(function (value) {
_this.cache[key] = value;
resolve();
});
}
});
};
LocalUpdateService.prototype.updateValue = function (key, localUpdate) {
var _this = this;
return new Promise(function (resolve) {
var newValue = localUpdate.function(_this.cache[key]);
_this.cache[key] = newValue;
_this.localForage.setItem(key, newValue).then(function () {
localUpdate.resolve(newValue);
resolve();
});
});
};
return LocalUpdateService;
}());
export { LocalUpdateService };
LocalUpdateService.decorators = [
{ type: Injectable },
];
/** @nocollapse */
LocalUpdateService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [LocalForageToken,] },] },
]; };
export function LOCAL_UPDATE_SERVICE_PROVIDER_FACTORY(parent, token) {
return parent || new LocalUpdateService(token);
}
;
export var LOCAL_UPDATE_SERVICE_PROVIDER = {
provide: LocalUpdateService,
deps: [
[new Optional(), new SkipSelf(), LocalUpdateService],
[new Inject(LocalForageToken)]
],
useFactory: LOCAL_UPDATE_SERVICE_PROVIDER_FACTORY
};