Skip to content

Instantly share code, notes, and snippets.

@sentanos
Created May 21, 2017 20:45
Show Gist options
  • Save sentanos/63df0588771d5cdd8e5c7b5d716274da to your computer and use it in GitHub Desktop.
Save sentanos/63df0588771d5cdd8e5c7b5d716274da to your computer and use it in GitHub Desktop.
// Dependencies
var events = require('events');
// Includes
var onNotification = require('./onNotification.js').func;
var getMessages = require('../getMessages.js').func;
// Args
exports.optional = ['jar'];
// Define
exports.func = function (args) {
var jar = args.jar;
var onMessage = new events.EventEmitter();
var waitingForRequest = false;
var latest;
getMessages({jar: jar, page: 1, limit: 1})
.then(function (initial) {
latest = initial.messages[0].id;
var notifications = onNotification({jar: jar});
notifications.on('data', function (name, message) {
if (name === 'NotificationStream' && message.Type === 'NewNotification') {
if (waitingForRequest) {
waitingForRequest = false;
} else {
getMessages({
jar: jar,
page: 1
})
.then(function (inbox) {
var messages = inbox.messages;
for (var i = messages.length - 1; i >= 0; i--) {
var message = messages[i];
var id = message.id;
if (id > latest) {
latest = id;
onMessage.emit('data', message);
}
}
});
}
} else if (name === 'FriendshipNotifications' && message.Type === 'FriendshipRequested') {
waitingForRequest = true;
}
});
notifications.on('error', function (err) {
onMessage.emit('error', err);
});
notifications.on('connect', function () {
onMessage.emit('connect');
});
onMessage.on('close', function () {
notifications.emit('close');
});
});
return onMessage;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment