node-telegram-api/lib/fetch.js

50 lines
1014 B
JavaScript
Raw Normal View History

2015-06-26 17:20:54 +00:00
import https from 'https';
import qs from 'qs';
2015-06-28 22:42:48 +00:00
export default function fetch(path, data) {
2015-06-26 17:20:54 +00:00
const post = qs.stringify(data);
return new Promise((resolve, reject) => {
const req = https.request({
hostname: 'api.telegram.org',
method: data ? 'POST' : 'GET',
path: '/bot' + path,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, response => {
2015-06-29 22:20:34 +00:00
return getBody(response).then(res => {
2015-06-26 17:20:54 +00:00
try {
let json = JSON.parse(res);
resolve(json);
} catch(e) {
reject(e);
}
2015-06-29 22:20:34 +00:00
}).catch(reject);
});
2015-06-26 17:20:54 +00:00
if (post) {
req.write(post);
}
req.end();
}).catch(err => {
console.error('Error sending request', err);
2015-06-26 17:20:54 +00:00
});
}
2015-06-29 22:20:34 +00:00
export function getBody(stream) {
let data = '';
return new Promise((resolve, reject) => {
stream.on('data', chunk => {
data += chunk;
});
stream.on('end', () => {
resolve(data);
});
stream.on('error', reject);
});
}