vuex-xhr-state
Version:
Use Vuex to manage the state of you're ajax calls.
92 lines (91 loc) • 3.58 kB
JavaScript
import { GLOBAL_GETTERS, GLOBAL_NAMESPACE, globalStore } from './globalXhrState';
var VuexXhrCreator = /** @class */ (function () {
// tslint:disable-next-line:no-any
function VuexXhrCreator(namespace, xhrStores) {
var _this = this;
this.invalidateCreators = [];
// tslint:disable-next-line:no-any
this.invalidateXhr = [];
this.plugin = function () {
var self = _this;
return function (store) {
self.store = store;
if (!(GLOBAL_NAMESPACE + '/' + GLOBAL_GETTERS.ANY_PENDING in store.getters)) {
store.registerModule('globalXhrState', globalStore);
}
store.registerModule(self.namespace, {
namespaced: true,
modules: self.modules,
});
};
};
// tslint:disable-next-line:no-any
this.reset = function ($store) {
for (var prop in _this.modules) {
if (!_this.modules.hasOwnProperty(prop))
continue;
$store.dispatch(_this.modules[prop].reset());
}
};
this.invalidateAll = function (fromNamespace) {
if (fromNamespace === void 0) { fromNamespace = []; }
if (!_this.store) {
return;
}
for (var key in _this.modules) {
if (_this.modules.hasOwnProperty(key) &&
_this.modules[key].options.cache &&
!_this.modules[key].options.alwaysRefetch) {
_this.store.dispatch(_this.modules[key].invalidateAll());
}
}
fromNamespace.push(_this.namespace);
for (var _i = 0, _a = _this.invalidateCreators; _i < _a.length; _i++) {
var creator = _a[_i];
if (fromNamespace.includes(creator.namespace)) {
continue;
}
creator.invalidateAll(fromNamespace);
}
for (var _b = 0, _c = _this.invalidateXhr; _b < _c.length; _b++) {
var xhr = _c[_b];
_this.store.dispatch(xhr.invalidateAll(), { root: true });
}
};
this.invalidates = function (vxs) {
if (vxs instanceof VuexXhrCreator || vxs[0] instanceof VuexXhrCreator) {
// @ts-ignore
return _this.invalidatesCreator(vxs);
}
// @ts-ignore
_this.invalidatesXhr(vxs);
};
this.invalidatesCreator = function (creators) {
if (!Array.isArray(creators)) {
creators = [creators];
}
_this.invalidateCreators = creators;
};
// tslint:disable-next-line:no-any
this.invalidatesXhr = function (xhr) {
if (!Array.isArray(xhr)) {
xhr = [xhr];
}
_this.invalidateXhr = xhr;
};
// tslint:disable-next-line:no-any
this.xhrStoresToModules = function (xhrStores) {
var modules = {};
xhrStores.forEach(function (xhrStore, index) {
xhrStore.setVuexXhrCreator(_this);
xhrStore.setNamespace(_this.namespace + '/xhr' + index);
modules['xhr' + index] = xhrStore;
});
return modules;
};
this.namespace = namespace;
this.modules = this.xhrStoresToModules(xhrStores);
}
return VuexXhrCreator;
}());
export { VuexXhrCreator };