Avoid Listener leaks by setting a max answer threshold

This commit is contained in:
Mahdi Dibaiee 2015-07-15 21:11:33 +04:30
parent fbe8d501a7
commit 2dd3dd2e80
5 changed files with 29 additions and 2 deletions

View File

@ -47,7 +47,7 @@ function fetch(path) {
}
_unirest2['default'].post('https://api.telegram.org/bot' + path).field(data).attach(files).end(function (response) {
if (response.statusType === 4 || response.statusType === 5) {
if (response.statusType === 4 || response.statusType === 5 || !response.body.ok) {
reject(response);
} else {
resolve(response.body);

View File

@ -14,6 +14,8 @@ function _inherits(subClass, superClass) { if (typeof superClass !== 'function'
var _events = require('events');
var ANSWER_THRESHOLD = 10;
/**
* Base class of all classes
*/
@ -67,7 +69,10 @@ var Base = (function (_EventEmitter) {
}
var chat = _this.properties.chat_id;
var answers = 0;
bot.on('update', function listener(result) {
answers += result.length;
var update = result.find(function (_ref) {
var message = _ref.message;
@ -86,6 +91,10 @@ var Base = (function (_EventEmitter) {
bot.removeListener('update', listener);
}
if (answers >= ANSWER_THRESHOLD) {
bot.removeListener('update', listener);
}
});
});
}

View File

@ -1,5 +1,7 @@
import {EventEmitter} from 'events';
const ANSWER_THRESHOLD = 10;
/**
* Base class of all classes
*/
@ -43,7 +45,10 @@ export default class Base extends EventEmitter {
}
const chat = this.properties.chat_id;
let answers = 0;
bot.on('update', function listener(result) {
answers += result.length;
const update = result.find(({message}) => {
// if in a group, there will be a reply to this message
if (chat < 0) {
@ -62,6 +67,10 @@ export default class Base extends EventEmitter {
bot.removeListener('update', listener);
}
if (answers >= ANSWER_THRESHOLD) {
bot.removeListener('update', listener);
}
});
});
}

View File

@ -1,6 +1,6 @@
{
"name": "telegram-api",
"version": "0.5.12",
"version": "0.5.20",
"description": "Control Telegram bots easily using the new Telegram API",
"main": "index.js",
"scripts": {

View File

@ -14,6 +14,8 @@ function _inherits(subClass, superClass) { if (typeof superClass !== 'function'
var _events = require('events');
var ANSWER_THRESHOLD = 10;
/**
* Base class of all classes
*/
@ -67,7 +69,10 @@ var Base = (function (_EventEmitter) {
}
var chat = _this.properties.chat_id;
var answers = 0;
bot.on('update', function listener(result) {
answers += result.length;
var update = result.find(function (_ref) {
var message = _ref.message;
@ -86,6 +91,10 @@ var Base = (function (_EventEmitter) {
bot.removeListener('update', listener);
}
if (answers >= ANSWER_THRESHOLD) {
bot.removeListener('update', listener);
}
});
});
}