Source: messaging/Connectors.js

/**
 * Licensed Materials - Property of IBM
 * IBM Cognos Products: Collaboration
 * (C) Copyright IBM Corp. 2017, 2018
 *
 * US Government Users Restricted Rights - Use, duplication or disclosure
 * restricted by GSA ADP Schedule Contract with IBM Corp.
 */

define([
	'../lib/@waca/core-client/js/core-client/ui/core/Class',
	'./connectors/index'
], function (Class, connectors) {
	'use strict';

	var Connectors = Class.extend( /** @lends Connectors */ {

		/**
		 * @desc Constructor for Connectors.
		 * @constructs Connectors
		 * @extends Class
		 * @public
		 * @param {object} options Options
		 * @param {object} options.glassContext The glass context
		 * @param {function} options.errorHandler Function to call when an error occurs
		 */
		init: function (options) {
			Connectors.inherited('init', this, arguments);
			this.glassContext = options.glassContext;
			if (!this.glassContext) {
				throw Error('Missing glassContext in options');
			}
			this.logger = this.glassContext.getCoreSvc('.Logger') || {
				log: console.log,
				error: console.error
			};
			this.errorHandler = options.errorHandler;

			// holds configured connectors
			this.connectors = [];
		},

		/**
		 * Discovers all the providers' and returns their connector instances.
		 * @instance
		 * @returns {promise}
		 */
		discover: function () {
			var ajaxSvc = this.glassContext.getCoreSvc('.Ajax');
			return ajaxSvc
				.ajax({
					type: 'GET',
					url: 'v1/collaboration/providers?flat=true'
				})
				.then(function (response) {
					return response.data.map(function (provider) {
						return this._handleSingleProvider(provider);
					}.bind(this));
				}.bind(this))
				.then(function (results) {
					return results
						// remove any unsupported/unknown connectors
						.filter(function (result) {
							return !!result;
						})
						// remove any connectors for which the user doesn't have the required capabilities
						.filter(function(result) {
							return result.checkUserCapabilities();
						});
				});
		},

		_handleSingleProvider: function (meta) {
			try {
				var Plugin = connectors[meta.type];
				if (Plugin) {
					var plugin = new Plugin({
						glassContext: this.glassContext,
						errorHandler: this.errorHandler,
						meta: meta
					});

					// ...and store it
					this.connectors.push(plugin);
					return plugin;
				} else {
					this.logger.error('Unable to load plugin: ' + meta.type);
				}
			} catch (error) {
				this.logger.error('Error while creating connector instance', error);
			}
			// null connectors will be removed below once all the promises are resolved
			return null;
		}
	});
	return Connectors;
});