mobx-roof
Version:
Simple React data management by mobx.
234 lines (206 loc) • 8.01 kB
JavaScript
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _temp;
exports.toMobxActions = toMobxActions;
exports.isMobxModelClass = isMobxModelClass;
var _mobx = require('mobx');
var _utils = require('../common/utils');
var _globalMiddleware = require('./globalMiddleware');
var _globalMiddleware2 = _interopRequireDefault(_globalMiddleware);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var count = 0;
var MobxModel = (_temp = _class = function () {
function MobxModel() {
var initData = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var middleware = arguments[1];
var _this = this;
var autorunMap = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var constants = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
_classCallCheck(this, MobxModel);
if (this.constructor !== MobxModel && this.constructor.uuid === Object.getPrototypeOf(this.constructor).uuid) {
throw new Error('[MobxModel] Can not immediately extend from MobxModel.');
}
this._actionStates = {};
this._middleware = middleware || _globalMiddleware2.default;
this._id = count++;
Object.keys(initData).forEach(function (key) {
if (constants[key] !== undefined) {
throw new Error('[MobxModel] data key "' + key + '" is defined in constants');
}
});
// check keys
this._dataKeys = Object.keys(initData).concat(Object.keys(constants));
this._checkDataKeys();
// add constants
var _constants = (0, _utils.mapValues)(constants, function (value) {
return {
enumerable: true,
configurable: true,
writable: false,
value: value
};
});
// add observable keys
Object.defineProperties(this, _constants);
(0, _mobx.extendObservable)(this, (0, _utils.toObservableObj)(initData));
// exec init before autorun
(0, _mobx.transaction)(function () {
return _this.init(initData);
});
// add auto run key
(0, _utils.each)(autorunMap, function (autorunFn) {
(0, _mobx.autorun)(autorunFn, _this);
});
}
_createClass(MobxModel, [{
key: 'init',
value: function init(initData) {
this.set(_extends({}, initData));
}
}, {
key: 'getID',
value: function getID() {
return this._id;
}
}, {
key: 'getActionState',
value: function getActionState(actionName) {
if (!this[actionName]) throw new Error('[MobxModel] Undefined action: ', actionName);
if (!this._actionStates[actionName]) {
(0, _mobx.extendObservable)(this._actionStates, _defineProperty({}, actionName, { loading: false, error: null }));
}
return this._actionStates[actionName];
}
}, {
key: 'toJS',
value: function toJS(key) {
var _this2 = this;
function parse(val) {
if (val instanceof MobxModel) {
return val.toJS();
}
if (Array.isArray(val) || (0, _mobx.isObservableArray)(val)) {
return val.map(function (item) {
return parse(item);
});
} else if ((0, _utils.isRegExp)(val)) {
return val;
} else if (val && (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') {
return (0, _utils.mapValues)(val, function (item) {
return parse(item);
});
}
return (0, _mobx.toJS)(val);
}
if (key) return parse(this[key]);
return this._dataKeys.reduce(function (json, key) {
json[key] = parse(_this2[key]);
return json;
}, {});
}
}, {
key: 'toJSON',
value: function toJSON(key) {
return this.toJS(key);
}
}, {
key: 'stringify',
value: function stringify() {
return JSON.stringify(this.toJS());
}
}, {
key: 'each',
value: function each(fn) {
var _this3 = this;
this._dataKeys.map(function (key) {
fn(_this3[key], key, _this3);
});
}
}, {
key: 'toString',
value: function toString() {
return this.constructor.name;
}
}, {
key: '_checkDataKeys',
value: function _checkDataKeys() {
var _this4 = this;
this._dataKeys.forEach(function (dataKey) {
if (_this4[dataKey]) {
throw new Error('[MobxModel] Data key "' + dataKey + '" is defined in prototype methods.');
}
});
}
}, {
key: 'set',
value: function set(key, val) {
var _this5 = this;
if (typeof key === 'string') {
this[key] = val;
return this;
}
(0, _mobx.runInAction)(function () {
return (0, _utils.mapValues)(key, function (item) {
return item;
}, _this5);
});
return this;
}
}, {
key: '_setActionState',
value: function _setActionState(actionName, val) {
this._actionStates[actionName] = val;
}
}, {
key: 'dataKeys',
get: function get() {
return this._dataKeys;
}
}, {
key: 'middleware',
set: function set(middleware) {
this._middleware = middleware;
},
get: function get() {
return this._middleware;
}
}]);
return MobxModel;
}(), _class.uuid = 0, _temp);
exports.default = MobxModel;
function toMobxActions(actions) {
return (0, _utils.mapValues)(actions, function (actionFn, actionName) {
return function () {
var _this6 = this;
for (var _len = arguments.length, actionArgs = Array(_len), _key = 0; _key < _len; _key++) {
actionArgs[_key] = arguments[_key];
}
var actionContext = this;
// Ensure actionState
this.getActionState(actionName);
// 1. add loading state and save the pre error
this._setActionState(actionName, { loading: true, error: this._actionStates[actionName].error });
// 2. exec action with hooks
return this.middleware.execAction({ actionFn: (0, _mobx.action)(actionFn), actionName: actionName, actionArgs: actionArgs, actionContext: actionContext }).then(function (payload) {
// 3. loaded success
_this6._setActionState(actionName, { loading: false, error: null });
return payload;
}).catch(function (error) {
// 4. loaded error
_this6._setActionState(actionName, { loading: false, error: error });
throw error;
});
};
});
}
function isMobxModelClass(target) {
return target === MobxModel || target.prototype instanceof MobxModel;
}