feathermost/js/pubsub.js

45 lines
1,021 B
JavaScript

const pubsub = (function() { "use strict";
const topics = [
"MESSAGES_NEW", // {endpoint, channel_id, create_at, user_id, message}
"MESSAGES_CHANGED",
"CHANNELS_NEW",
"CHANNELS_CHANGED",
"USERS_NEW",
"USERS_CHANGED",
"CHANNEL_MEMBERS_NEW",
"CHANNEL_MEMBERS_REMOVED",
"CHANNEL_READ", // {endpoint, channel_id}
];
let subscribers = Object.create(null);
for (let topic of topics) {
subscribers[topic] = [];
}
function subscribe(topic, callback) {
assert(subscribers[topic], `Pubsub topic '${topic}' exists`);
subscribers[topic].push(callback);
}
function publish(topic, payload) {
assert(subscribers[topic], `Pubsub topic '${topic}' exists`);
const amountSubs = subscribers[topic].length;
if (amountSubs == 0) {
console.warn(`Pubsub event with topic '${topic}' without any subscribers`);
} else {
console.debug(`Pubsub event with topic '${topic}' with ${amountSubs} subscribers`);
}
for (let subscriber of subscribers[topic]) {
subscriber(payload);
}
}
return {subscribe, publish};
})();