UNPKG

@textback/notification-widget

Version:

TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project.

68 lines (55 loc) 2.1 kB
import apiErrorHandler from "./utils/apiErrorHandler"; import 'whatwg-fetch'; import Widget from './widget/widget.js'; import {EVENTS, Observer} from './events/observer.js'; import {deeplinkUpdater} from './utils/loadDeepLink.js'; require('es6-promise').polyfill(); export default class SDK { constructor() { this.widgets = {}; this._deeplinkUpdater = deeplinkUpdater; } initWidget(config, preventViewCounting = false) { if (config && config.widgetId) { const widget = new Widget(config, this); this.widgets[config.widgetId] = widget.initialize(); this.widgets[config.widgetId].then(widget => { Observer.trigger(EVENTS.WIDGET_INIT, {widgetId: config.widgetId}); // First of all, this is a restriction on the count of views for textback settings page ( = for widget preview) if (preventViewCounting) return; this.countWidgetView(widget); }, err => console.error(err)); return this.widgets[config.widgetId]; } else { throw new Error('Widget id is not defined'); } } countWidgetView(widget) { return fetch(`${widget.initialConfig.apiPath}/endUserNotifications/subscriptions/notificationWidget/views`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'accountId': widget.config.accountId, 'widgetId': widget.id }) }).then(apiErrorHandler); } getWidget(widgetId) { return this.widgets[widgetId] ? this.widgets[widgetId] : null; } on(eventName, fn) { return Observer.on(eventName, fn); } getDeeplinkUpdater(widgetId) { let _getWidget = this.widgets[widgetId]; if (!_getWidget) return null; return _getWidget.then(x => { return this._deeplinkUpdater( x.initialConfig.apiPath, x.deeplink.split('_')[1] ); }); } }