UNPKG

@magicbell/core

Version:
58 lines 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.pushEventAggregator = void 0; exports.connectToAbly = connectToAbly; exports.handleAblyEvent = handleAblyEvent; const tslib_1 = require("tslib"); const Ably = tslib_1.__importStar(require("ably")); const get_js_1 = tslib_1.__importDefault(require("lodash/get.js")); const mittly_1 = tslib_1.__importDefault(require("mittly")); const index_js_1 = tslib_1.__importDefault(require("../models/Notification/index.js")); const ajax_js_1 = require("./ajax.js"); const pushEventAggregator = (0, mittly_1.default)(); exports.pushEventAggregator = pushEventAggregator; /** * Open an authenticated connection to ably. * * @param config The configuration used to open the connection. */ function connectToAbly(config, authServerUrl = 'https://api.magicbell.com') { const authUrl = `${authServerUrl}/${config.ws.authUrl}`; const authHeaders = { 'X-MAGICBELL-API-KEY': config.apiKey }; if (config.userEmail) authHeaders['X-MAGICBELL-USER-EMAIL'] = config.userEmail; if (config.userExternalId) authHeaders['X-MAGICBELL-USER-EXTERNAL-ID'] = config.userExternalId; if (config.userKey) authHeaders['X-MAGICBELL-USER-HMAC'] = config.userKey; const client = new Ably.Realtime({ authUrl, authHeaders, authMethod: 'POST', log: { level: 0 }, transports: ['web_socket'], }); return client; } /** * Publish an ably event to the push event emitter. If the push event contains * the ID of a notification, this is fetched before emitting the event. * * @param event Ably event */ function handleAblyEvent(event) { const name = event.name.replace(/\//gi, '.'); const eventData = event.data; if (eventData.client_id && eventData.client_id === (0, get_js_1.default)(ajax_js_1.api, 'defaults.headers.X-MAGICBELL-CLIENT-ID')) { return Promise.resolve(); } if (typeof eventData.id === 'string') { const notification = new index_js_1.default({ id: eventData.id }); return notification.fetch().then(() => { pushEventAggregator.emit(name, notification); }); } pushEventAggregator.emit(name, eventData); return Promise.resolve(); } //# sourceMappingURL=realtime.js.map