Skip to content

Instantly share code, notes, and snippets.

@karn09
Created April 18, 2017 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karn09/6428ba16e245e27b0a310cee917601a7 to your computer and use it in GitHub Desktop.
Save karn09/6428ba16e245e27b0a310cee917601a7 to your computer and use it in GitHub Desktop.
fetch all messages, and then generate a frequency object based on replies sent for dates specified.
const kapi = require('../index')({
type: 'prod',
token: 'TOKEN'
})
const Promise = require('bluebird');
const _ = require('lodash');
const date13th = '2017-04-13';
const date14th = '2017-04-14';
kapi.users.fetchAll()
.then((usersResp) => {
const usersHash = usersResp.data.reduce((acc, user) => {
acc[user.id] = user.attributes.name;
return acc;
}, {})
const replyFreq = {};
let next;
let seen = 0;
function getAllMessagesIterator(page) {
return getAllMessages(page)
.then((messagesResp) => {
next = messagesResp.links.next;
const messages = messagesResp.data;
return Promise.each(messages, (message) => {
const userId = _.get(message, 'relationships.createdBy.data.id');
const direction = _.get(message, 'attributes.direction');
const createdAt = _.get(message, 'attributes.createdAt');
const userName = usersHash[userId];
if (!userId) return Promise.resolve();
if (!replyFreq[userId]) replyFreq[userId] = {};
if (!replyFreq[userId].name) replyFreq[userId].name = userName;
if (createdAt.startsWith(date13th) && direction === 'out') {
seen++;
if (!replyFreq[userId][date13th]) replyFreq[userId][date13th] = 1;
if (replyFreq[userId] && replyFreq[userId][date13th]) replyFreq[userId][date13th]++;
}
if (createdAt.startsWith(date14th) && direction === 'out') {
seen++;
if (!replyFreq[userId][date14th]) replyFreq[userId][date14th] = 1;
if (replyFreq[userId] && replyFreq[userId][date14th]) replyFreq[userId][date14th]++;
}
return Promise.resolve();
})
})
.then(() => {
console.log(seen)
console.log(replyFreq)
if (next) return getAllMessagesIterator(next);
return replyFreq;
})
}
return getAllMessagesIterator()
.then((freq) => {
console.log(freq)
})
});
function getAllMessages(page) {
return kapi.messages.getAll(page);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment