UNPKG

@actorize/core

Version:

Actorize helps building scalable js apps with a messaging system

45 lines 1.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createStore = void 0; function createStore() { let messages = []; const callbacks = {}; const popMessages = async (recipient, keepMessage = false) => { const relevantMessages = messages.filter((e) => e.recipient === recipient || recipient === '*'); if (!keepMessage) { messages = messages.filter((e) => !(e.recipient === recipient || recipient === '*')); } return relevantMessages; }; const pushMessage = async (recipient, payload, sender) => { messages.push({ recipient, payload, sender, }); if (typeof callbacks[recipient] === 'function') { setTimeout(() => { callbacks[recipient](); }, 0); } }; const subscribe = (recipient, callback) => { const cb = async () => { const msgs = await popMessages(recipient); if (msgs.length) { callback(msgs); } }; callbacks[recipient] = cb; return () => { delete callbacks[recipient]; }; }; return { pushMessage, popMessages, subscribe, }; } exports.createStore = createStore; //# sourceMappingURL=store.js.map