node-telegram-api/lib/fetch.js

40 lines
840 B
JavaScript
Raw Normal View History

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