72 lines
1.7 KiB
JavaScript
72 lines
1.7 KiB
JavaScript
|
EmbarkJS.Messages.Orbit = {};
|
||
|
|
||
|
EmbarkJS.Messages.Orbit.sendMessage = function(options) {
|
||
|
var topics = options.topic || options.topics;
|
||
|
var data = options.data || options.payload;
|
||
|
|
||
|
if (topics === undefined) {
|
||
|
throw new Error("missing option: topic");
|
||
|
}
|
||
|
|
||
|
if (data === undefined) {
|
||
|
throw new Error("missing option: data");
|
||
|
}
|
||
|
|
||
|
if (typeof topics === 'string') {
|
||
|
topics = topics;
|
||
|
} else {
|
||
|
// TODO: better to just send to different channels instead
|
||
|
topics = topics.join(',');
|
||
|
}
|
||
|
|
||
|
this.orbit.join(topics);
|
||
|
|
||
|
var payload = JSON.stringify(data);
|
||
|
|
||
|
this.orbit.send(topics, data);
|
||
|
};
|
||
|
|
||
|
EmbarkJS.Messages.Orbit.listenTo = function(options) {
|
||
|
var self = this;
|
||
|
var topics = options.topic || options.topics;
|
||
|
|
||
|
if (typeof topics === 'string') {
|
||
|
topics = topics;
|
||
|
} else {
|
||
|
topics = topics.join(',');
|
||
|
}
|
||
|
|
||
|
this.orbit.join(topics);
|
||
|
|
||
|
var messageEvents = function() {
|
||
|
this.cb = function() {};
|
||
|
};
|
||
|
|
||
|
messageEvents.prototype.then = function(cb) {
|
||
|
this.cb = cb;
|
||
|
};
|
||
|
|
||
|
messageEvents.prototype.error = function(err) {
|
||
|
return err;
|
||
|
};
|
||
|
|
||
|
var promise = new messageEvents();
|
||
|
|
||
|
this.orbit.events.on('message', (channel, message) => {
|
||
|
// TODO: looks like sometimes it's receving messages from all topics
|
||
|
if (topics !== channel) return;
|
||
|
self.orbit.getPost(message.payload.value, true).then((post) => {
|
||
|
var data = {
|
||
|
topic: channel,
|
||
|
data: post.content,
|
||
|
from: post.meta.from.name,
|
||
|
time: (new Date(post.meta.ts))
|
||
|
};
|
||
|
promise.cb(post.content, data, post);
|
||
|
});
|
||
|
});
|
||
|
|
||
|
return promise;
|
||
|
};
|
||
|
|