node-telegram-api/build/functions/fetch.js

74 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-07-05 13:36:27 +00:00
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = fetch;
exports.getBody = getBody;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _unirest = require('unirest');
2015-07-05 13:36:27 +00:00
var _unirest2 = _interopRequireDefault(_unirest);
2015-07-05 13:36:27 +00:00
function fetch(path) {
var data = arguments[1] === undefined ? {} : arguments[1];
return new Promise(function (resolve, reject) {
var files = {};
2015-07-05 13:36:27 +00:00
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(data)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (data[key].file) {
files[key] = data[key].file;
delete data[key];
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
2015-07-05 13:36:27 +00:00
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
_unirest2['default'].post('https://api.telegram.org/bot' + path).field(data).attach(files).end(function (response) {
if (response.statusType === 4 || response.statusType === 5) {
reject(response);
} else {
resolve(response.body);
2015-07-05 13:36:27 +00:00
}
});
});
}
function getBody(stream) {
var data = '';
return new Promise(function (resolve, reject) {
stream.on('data', function (chunk) {
data += chunk;
});
stream.on('end', function () {
resolve(data);
});
stream.on('error', reject);
});
}