@loona/react
Version:
App State Management done with GraphQL (react integration)
90 lines • 3.32 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { METADATA_KEY, isMutation, getMutation, isMutationAsAction, getNameOfMutation, buildContext, withUpdates, buildGetCacheKey, getActionType, buildActionFromResult, buildActionFromError, } from '@loona/core';
var Loona = /** @class */ (function () {
function Loona(client, manager, states) {
var _this = this;
this.client = client;
this.manager = manager;
this.effects = {};
manager.getClient = function () { return client; };
states.forEach(function (state) {
var instance = new state();
var meta = state[METADATA_KEY];
_this.manager.addState(instance, meta);
_this.addEffects(instance, meta.effects);
});
}
Loona.prototype.dispatch = function (action) {
if (isMutation(action)) {
var mutation = getMutation(action);
var config = __assign({ mutation: mutation }, action);
this.wrapMutation(this.client.mutate(withUpdates(config, this.manager)), config);
}
else {
this.runEffects(__assign({ type: getActionType(action) }, action));
}
};
Loona.prototype.addEffects = function (instance, meta) {
var _this = this;
if (!meta) {
return;
}
var _loop_1 = function (type) {
if (!this_1.effects[type]) {
this_1.effects[type] = [];
}
meta[type].forEach(function (_a) {
var propName = _a.propName;
_this.effects[type].push(instance[propName].bind(instance));
});
};
var this_1 = this;
for (var type in meta) {
_loop_1(type);
}
};
Loona.prototype.runEffects = function (action) {
var type = action.type;
var cache = this.client.cache;
var context = __assign({}, buildContext({
cache: cache,
getCacheKey: buildGetCacheKey(cache),
}, this.client), { dispatch: this.dispatch.bind(this) });
if (isMutationAsAction(action)) {
type = getNameOfMutation(action.options.mutation);
}
var effectsToRun = this.effects[type];
if (effectsToRun) {
effectsToRun.forEach(function (effect) {
effect(action, context);
});
}
};
Loona.prototype.wrapMutation = function (mutationPromise, config, shouldThrow) {
var _this = this;
if (shouldThrow === void 0) { shouldThrow = true; }
mutationPromise
.then(function (result) {
_this.runEffects(buildActionFromResult(config, result));
})
.catch(function (error) {
_this.runEffects(buildActionFromError(config, error));
if (shouldThrow) {
throw error;
}
});
};
return Loona;
}());
export { Loona };
//# sourceMappingURL=client.js.map