Skip to content

Commit

Permalink
added events
Browse files Browse the repository at this point in the history
  • Loading branch information
Vladimir Yazykov committed Jan 27, 2019
1 parent 2035c27 commit f0a727c
Show file tree
Hide file tree
Showing 9 changed files with 483 additions and 35 deletions.
36 changes: 34 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Javascript библиотека для работы с AmoCRM
const AmoCRM = require( 'amocrm-js' );

const crm = new AmoCRM({
domain: 'domain' // логин пользователя в портале, где адрес портала mydomain.amocrm.ru
domain: 'domain', // логин пользователя в портале, где адрес портала mydomain.amocrm.ru
auth: {
login: 'mylogin',
hash: 'mytesthash', // API-ключ доступа
Expand Down Expand Up @@ -140,9 +140,41 @@ crm.Lead.findById( 123 )

```js
// список идентификаторов сделок
crm.Lead.remove([ 12 345, 568944 ])
crm.Lead.remove([ 12345, 568944 ])

// удаление отедльной сделки
crm.Lead.findById( 123 )
.then( lead => lead.remove());
```

## Работа с событиями

В настоящий момент доступны следующие события:

1. connection:beforeReconnect
2. connection:beforeConnect
3. connection:authError
4. connection:connected
5. connection:error

Добавление обработчика:

```javascript
crm.on( 'connection:error', () => console.log( 'Ошибка соединения' ));
```

Удаление обработчика:

```javascript
const handler = () => console.log( 'Ошибка соединения' );
crm.on( 'connection:error', handler );

// удалить конкретный обработчик
crm.off( 'connection:error', handler );

// удалить все обработчики конкретного события
crm.off( 'connection:error' );

// удалить все обработчики всех событий
crm.off();
```
51 changes: 42 additions & 9 deletions dist/AmoCRM.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

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 _EventResource2 = require('./base/EventResource');

var _EventResource3 = _interopRequireDefault(_EventResource2);

var _AmoConnection = require('./base/AmoConnection');

var _AmoConnection2 = _interopRequireDefault(_AmoConnection);
Expand All @@ -18,21 +22,45 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var AmoCRM = function () {
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AmoCRM = function (_EventResource) {
_inherits(AmoCRM, _EventResource);

function AmoCRM(options) {
_classCallCheck(this, AmoCRM);

var _this = _possibleConstructorReturn(this, (AmoCRM.__proto__ || Object.getPrototypeOf(AmoCRM)).call(this));

if (!options) {
throw new Error('Wrong configuration');
}
this._options = options;
this._request = new _PrivateDomainRequest2.default(options.domain);
this._connection = new _AmoConnection2.default(this._request, options.auth);
_this._options = options;
_this._request = new _PrivateDomainRequest2.default(options.domain);
_this._connection = new _AmoConnection2.default(_this._request, options.auth);

this.assignFactories();
_this.registerEvents();
_this.assignFactories();
return _this;
}

_createClass(AmoCRM, [{
key: 'registerEvents',
value: function registerEvents() {
var _this2 = this;

this.proxyEventHandlers('connection', _AmoConnection2.default.EVENTS, this._connection);
this._connection.on('error', function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}

return _this2.triggerEvent.apply(_this2, ['error'].concat(args));
});
}
}, {
key: 'assignFactories',
value: function assignFactories() {
var builder = new _ResourceFactoryBuilder2.default(this._request),
Expand All @@ -47,24 +75,29 @@ var AmoCRM = function () {
}, {
key: 'request',
get: function get() {
var _this = this;
var _this3 = this;

return {
get: function get() {
var _request;

return (_request = _this._request).get.apply(_request, arguments);
return (_request = _this3._request).get.apply(_request, arguments);
},
post: function post() {
var _request2;

return (_request2 = _this._request).post.apply(_request2, arguments);
return (_request2 = _this3._request).post.apply(_request2, arguments);
}
};
}
}, {
key: 'connection',
get: function get() {
return this._connection;
}
}]);

return AmoCRM;
}();
}(_EventResource3.default);

module.exports = AmoCRM;
89 changes: 80 additions & 9 deletions dist/base/AmoConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,73 @@ var _apiUrls = require('../apiUrls.js');

var _apiUrls2 = _interopRequireDefault(_apiUrls);

var _EventResource2 = require('./EventResource');

var _EventResource3 = _interopRequireDefault(_EventResource2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var AmoConnection = function () {
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var AmoConnection = function (_EventResource) {
_inherits(AmoConnection, _EventResource);

function AmoConnection(request) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

_classCallCheck(this, AmoConnection);

this._request = request;
this._options = options;
this._isConnected = false;
var _this = _possibleConstructorReturn(this, (AmoConnection.__proto__ || Object.getPrototypeOf(AmoConnection)).call(this));

_this._request = request;
_this._options = options;
_this._isConnected = false;
return _this;
}

_createClass(AmoConnection, [{
key: 'reconnectAt',
value: function reconnectAt(date) {
var _this2 = this;

var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60 * 1000;
var accuracyTime = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60 * 1000;

delete this._reconnectTimeout;

var timeout = void 0;
var self = this,
onReconnect = new Promise(function check(resolve, reject) {
if (self._reconnectTimeout !== timeout) {
return reject();
}

timeout = setTimeout(function () {
var now = new Date();

if (now > date - accuracyTime) {
return resolve();
}

check(resolve, reject);
}, delay);

self._reconnectTimeout = timeout;
});

return onReconnect.then(function () {
_this2.triggerEvent('beforeReconnect', true);
return _this2.connect();
});
}
}, {
key: 'connect',
value: function connect() {
var _this = this;
var _this3 = this;

if (this._isConnected) {
return Promise.resolve(true);
Expand All @@ -33,6 +81,7 @@ var AmoConnection = function () {
login = _options.login,
password = _options.password,
hash = _options.hash,
reconnection = _options.reconnection,
data = {
USER_LOGIN: login
};
Expand All @@ -44,17 +93,37 @@ var AmoConnection = function () {
data['USER_PASSWORD'] = password;
}

this.triggerEvent('beforeConnect', this);

return this._request.post(_apiUrls2.default.auth, data, {
headers: { 'Content-Type': 'application/json' },
response: {
dataType: 'json',
saveCookies: true
}
}).then(function (data) {
_this._isConnected = data.response.auth === true;
return _this._isConnected;
if (reconnection) {
_this3.reconnectAt(_this3._request.expires, reconnection.checkDelay);
}

_this3._isConnected = data.response.auth === true;

if (_this3._isConnected) {
_this3.triggerEvent('connected', _this3);
return true;
}

var e = new Error('Auth Error');
e.data = data.response;

_this3.triggerEvent('authError', e, _this3);
_this3.triggerEvent('error', e, _this3);

return false;
}).catch(function (e) {
throw new Error('Connection Error: ' + e.message);
_this3.triggerEvent('error', e, _this3);

throw e;
});
}
}, {
Expand All @@ -65,6 +134,8 @@ var AmoConnection = function () {
}]);

return AmoConnection;
}();
}(_EventResource3.default);

AmoConnection.EVENTS = ['beforeReconnect', 'beforeConnect', 'authError', 'connected', 'error'];

module.exports = AmoConnection;
81 changes: 81 additions & 0 deletions dist/base/EventResource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"use strict";

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; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var EventResource = function () {
function EventResource() {
_classCallCheck(this, EventResource);

this._events = {};
}

_createClass(EventResource, [{
key: "proxyEventHandlers",
value: function proxyEventHandlers(prefix, events, target) {
var _this = this;

events.forEach(function (event) {
return target.on(event, function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}

var selfEvent = prefix + ":" + event;
_this.triggerEvent.apply(_this, [selfEvent].concat(args));
});
});
}
}, {
key: "on",
value: function on(event, handler) {
if (!this._events[event]) {
this._events[event] = [];
}

this._events[event].push(handler);
return this;
}
}, {
key: "off",
value: function off(event, handler) {
if (!event) {
this._events = [];
return this;
}

if (!handler) {
delete this._events[event];
}

var index = this._events[event].findIndex(handler);

if (!index) {
return this;
}

this._events[event].splice(index, 1);
return this;
}
}, {
key: "triggerEvent",
value: function triggerEvent(event) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}

if (!this._events[event]) {
return;
}

this._events[event].forEach(function (handler) {
return handler.apply(undefined, args);
});
}
}]);

return EventResource;
}();

module.exports = EventResource;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "amocrm-js",
"version": "1.0.4",
"version": "1.0.5",
"description": "JS Library for AmoCRM",
"main": "dist/AmoCRM.js",
"directories": {
Expand Down
Loading

0 comments on commit f0a727c

Please sign in to comment.