UNPKG

@barteh/react-withservice

Version:

A HOC injects and manages observable data services in a react Component

320 lines (258 loc) 14.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.withService = void 0; var _react = _interopRequireWildcard(require("react")); var _rxjs = _interopRequireDefault(require("rxjs")); var _asService = require("@barteh/as-service"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _extends() { _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; }; return _extends.apply(this, arguments); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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; } /** *injects services into react component no need to subscribe or unsubscribe * @param {an object contains services and actions} srvs */ var withService = function withService(srvs) { return function (Comp) { var _temp; return _temp = /*#__PURE__*/ function (_Component) { _inherits(innerWithServer, _Component); function innerWithServer(props) { var _this; _classCallCheck(this, innerWithServer); _this = _possibleConstructorReturn(this, _getPrototypeOf(innerWithServer).call(this, props)); _defineProperty(_assertThisInitialized(_this), "sub", null); _defineProperty(_assertThisInitialized(_this), "data", {}); _defineProperty(_assertThisInitialized(_this), "actions", {}); _defineProperty(_assertThisInitialized(_this), "services", {}); _defineProperty(_assertThisInitialized(_this), "state", {}); _defineProperty(_assertThisInitialized(_this), "lastProps", {}); _defineProperty(_assertThisInitialized(_this), "notRequireSubscriptions", []); _defineProperty(_assertThisInitialized(_this), "unmounted", false); _defineProperty(_assertThisInitialized(_this), "afterfifo", []); _defineProperty(_assertThisInitialized(_this), "canRender", false); _this.retry = _this.retry.bind(_assertThisInitialized(_this)); return _this; } _createClass(innerWithServer, [{ key: "retry", value: function retry() { this.setServices(this.props); } }, { key: "compareParams", value: function compareParams(a, b) { return JSON.stringify(a) === JSON.stringify(b); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unmounted = true; if (this.sub) this.sub.unsubscribe(); this.lastProps = {}; } }, { key: "setServices", value: function setServices(props) { var _this2 = this, _Rx$Observable; this.notRequireSubscriptions.map(function (a) { return a.unsubscribe(); }); this.notRequireSubscriptions = []; if (srvs.services === undefined) return; this.canRender = true; if (this.sub) this.sub.unsubscribe(); var names = []; var observables = []; var notRequireObservables = []; var requiredNames = []; var notRequireNames = []; var errorObservables = []; this.traceServices = []; var keys = Object.keys(srvs.services); var ready = new Array(keys.length); keys.map(function (a, i) { names.push(a); var srv = srvs.services[a]; var source = srv.source !== undefined ? srv.source : srv; var service = source !== undefined && source.$$isAsService ? source : new _asService.AsService(source); var params = srv.params ? srv.params(props) : []; if (srv.isRequire) { requiredNames.push(a); observables.push(service.Observable.apply(service, _toConsumableArray(params))); } else { notRequireNames.push(a); notRequireObservables.push(service.Observable.apply(service, _toConsumableArray(params))); } errorObservables.push(service.ErrorObservable.apply(service, _toConsumableArray(params))); ready[i] = !srv.isRequire || service.getState.apply(service, _toConsumableArray(params)) !== 'start'; var trace = false; if (!_this2.compareParams(_this2.lastProps[a], params)) { if (!srv.onBeforeCall || srv.onBeforeCall && srv.onBeforeCall(props)) { trace = srv.reload; var Fn = srv.reload ? service.load : service.get; Fn.call.apply(Fn, [service].concat(_toConsumableArray(params))).then(function (b) { if (srv.onAfterCall) { ready[i] = true; srv.onAfterCall(props, b); } return b; }).catch(function (e) { if (srv.onError) { ready[i] = false; srv.onError(e, props); } _this2.lastProps[a] = []; if (!_this2.unmounted) _this2.setState({ error: true }); return e; }); } } _this2.traceServices.push(trace); _this2.lastProps[a] = props; return ""; }); ready.map(function (a) { _this2.canRender = _this2.canRender && a; return false; }); if (this.canRender) { if (!this.unmounted) this.setState({ canRender: true }); } notRequireObservables.map(function (b, j) { _this2.notRequireSubscriptions.push(b.subscribe(function (c) { if (!_this2.unmounted) _this2.setState(_defineProperty({}, notRequireNames[j], c)); return ""; })); return ""; }); this.sub = (_Rx$Observable = _rxjs.default.Observable).combineLatest.apply(_Rx$Observable, observables).subscribe(function (a) { var o = { canRender: true }; a.map(function (b, i) { o[requiredNames[i]] = b; return ""; }); o["error"] = false; if (!_this2.unmounted) _this2.setState(o); }); } }, { key: "UNSAFE_componentWillReceiveProps", value: function UNSAFE_componentWillReceiveProps(nextProps) { this.setServices(nextProps); return; } }, { key: "UNSAFE_componentWillMount", value: function UNSAFE_componentWillMount() { this.lastProps = {}; var services = srvs.services, actions = srvs.actions; var outstate = { services: {} }; for (var ser in services) { outstate.services[ser] = services[ser].service; } this.services = outstate.services; if (actions !== undefined) { var _loop = function _loop(act) { var action = actions[act]; action.service = action.action !== undefined ? action.action : action; var fn = function fn() { for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) { params[_key] = arguments[_key]; } // if (action.service.$$isAsService) { let ret = action .service // .load .call(action.service, ...params) .then(a => { if // (action.onAfterCall) action.onAfterCall(a); return a; // }) .catch(e => { if (action.onError) action.onError(e); // return e; }); return ret; } else if (typeof action.service === "function" || action.service.$$isAsService) { return new Promise(function (res, rej) { try { var func = action.service.$$isAsService ? action.service.getLoader() : action.service; var mapper = action.service.$$isAsService ? action.service.getMapper() : undefined; var beforMapper = func.call.apply(func, [action.service].concat(params)); var retval = mapper ? mapper.apply(void 0, params) : beforMapper; if (retval instanceof Promise) { retval.then(function (a) { res(a); if (action.onAfterCall) { action.onAfterCall(a); } }).catch(function (e) { rej(e); if (action.onError) action.onError(e); }); } else { res(retval); } } catch (e) { if (action.onError) action.onError(e); rej(e); } }); } else { return new Promise(function (res, rej) { try { res(action.service); if (action.onAfterCall) action.onAfterCall(action.service); } catch (e) { rej(e); if (action.onError) action.onError(e); } }); } }; var fn2 = fn.bind(action); outstate[act] = fn2; }; for (var act in actions) { _loop(act); } } this.setServices(this.props); if (!this.unmounted) this.setState(outstate); } }, { key: "render", value: function render() { return _react.default.createElement(_react.default.Fragment, null, this.state.error && srvs.error !== undefined && _react.default.createElement(srvs.error, _extends({ retry: this.retry }, this.props)), !this.state.error && !this.state.canRender && srvs.loading !== undefined && _react.default.createElement(srvs.loading, null), this.state.canRender && !this.state.error && _react.default.createElement(Comp, _extends({}, this.props, this.state))); } }]); return innerWithServer; }(_react.Component), _temp; }; }; exports.withService = withService; var _default = withService; exports.default = _default;