I would like to use the gitter api to get all the messages from a room.
What I need to do is to send the get api request with e.g. 50 items, onComplete I need to send another request with 50 items and skip 50 items I already received. Do this request till they won't return any items. So:
- send api request
- json parse it
- : request has items
- make a sql query with this items
- proceed the query
- send next api request (recursion?)
- ? if no more items in next api request - show done message
- : request does not have items
- abort with message
I am trying Promises for that, but I got a bit confused with them and don't know, if I am doing everything right. The main problem is the next Api call and callback if all calls are done. This is my code:
class Bot {
//...
_mysqlAddAllMessages(limit, skip) {
promise('https://api.gitter.im/v1/rooms/' + this.room + '/chatMessages' +
'?access_token=' + config.token + '&limit=' + limit + '&skip=' + skip)
.then(function (response) {
return new Promise(function (resolve, reject) {
response = JSON.parse(response);
if (response.length) {
console.log(`Starting - limit:${limit}, skip:${skip}`);
resolve(response);
}
})
}).then(response => {
let messages = response,
query = 'INSERT INTO messages_new (user_id, username, message, sent_at) VALUES ';
for (let message of messages) {
let userId = message.fromUser.id,
username = message.fromUser.username,
text = message.text.replace(/["\\]/g, '|'),
date = message.sent;
query += '("' + userId + '", "' + username + '", "' + text + '", "' + date + '"), ';
}
query = query.substr(0, query.length - 2);
return new Promise((resolve, reject) => {
this.mysql.getConnection((error, connection) => {
connection.query(query, (err) => {
if (err) {
reject(`Mysql Error: ${err}`);
} else {
connection.release();
resolve(console.log(`Added ${messages.length} items.`));
}
});
});
});
})
.then(()=> {
// what to do here
return this._mysqlAddAllMessagesf(limit, skip += limit)
})
.catch(function (er) {
console.log(er);
})
.finally(function () {
console.log('Message fetching completed.');
});
}
}
let bot = new Bot();
bot._mysqlAddAllMessages(100, 0);
Maybe you can check and help me? Or provide similar code for such things?
update
Here is what I refactored the code to: jsfiddle