Common Functions

Below is the list of common functions provided by IBM® webMethods Embed SDK:

CAUTION:
While consuming the IBM webMethods Embed SDK, follow the promises paradigm, as each function inside the SDK supports only promises.
  1. SDK Initializer

    There are two ways to initialize the Embed SDK in a front-end application:

    • Using Embed API request
    • Using init() function
    1. Initializing Embed SDK using Embed API request
      Perform the following steps to initialize the Embed SDK using the Embed API request:
      1. Send initializer API request to Embed server

        Send the following initializer API request from your backend server to Embed server:

        Request details:

        • URL: /saas/webmethods-embed/v2/saas/webmethods-embed/synergy/initializer/create
        • Method: POST
        • Headers:
          • identifier: , //Retrieve the identifier by navigating to Settings > Developer Tools > Identifier in the Embed Admin Portal
          • jwt: (OPTIONAL header)
            Note: If you want to login the user along with initializing the SDK, you need to send a JWT signed string which is encrypted using an API_KEY. Given below is the sample code to create a JWT:
            const jsonwebtoken = require('jsonwebtoken')
            const API_KEY = <API_KEY> // Settings -> Developer Tools -> API Key 
            const user = 
            { consumer_uid : ,// 
            domain : , // Settings -> Developer Tools -> Domain 
            plan : '', 
            time : new Date().getTime()} 
            var jwt = jsonwebtoken.sign(user, API_KEY); 
            console.log(jwt); 
      2. Send the hash key from your backend server to frontend server

        If the request is completed successfully, the Embed server sends a hash key in response.

      3. Use the fetchInitializerKeys function to fetch initializer keys

        fetchInitializerKeys({String hash_key, String api_host(OPTIONAL)}, callback) This function fetches the keys required to initialize the Embed SDK and returns the Embed object. It performs a handshake with the API server and checks whether the provided key combination is valid or not. Since the basic communication rules are set by this function, it must be called before any other function provided by the SDK.

        FlowEmbed.revalidateKeys(IDENTIFIER, callback) When you call this function, it allows Embed SDK to use older initializers. On each refresh of the page, we cannot make a new initializer call to the backend component. Instead of making a new API call, use this function to verify whether the older communication is working or not. If the validation is correct then it returns an Embed object as following:

        FlowEmbed.revalidateKeys(IDENTIFIER, (err, embed) => {
        
           if(embed) {
               window.Embed = embed;
               start(embed);
               return cb(err,embed);
           }
          // below is the function call to initialize embed sdk
           return initiateEmbedSDK(cb)
        })
        

        If the identifier doesn’t match or it fails to use an older initializer then the function throws an error “Initialization failed”. On receiving this error, you have to make a new initializer request to the backend server.

        Sample Code to initialize the Embed SDK using API request:

        function start(Embed) {
        
        Embed.on('logout', logoutUser);
        }
        function initiateEmbedSDK(cb) {
        const API_DOMAIN = "" // Your backend server domain
        const API_INITIATE_ROUTE = "" // Newly created route for SDK initializer in your backend component
        const IDENTIFIER = "" // Settings -> Developer Tools -> Identifier
        const USERNAME = ""  // <Any string>
        const EMBED_API_ENDPOINT = "" // Custom Embed API Server
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
           if (this.readyState == 4 && this.status == 200) {
               var hash_key = null;
               try{
                   hash_key =  JSON.parse(this.responseText).output.key;
               } catch(e){
                   hash_key = "";
               }
               if(!hash_key) {
                   try{   
                       showLoginErrorMessage(JSON.parse(this.responseText).error.message);
                       return;
                   } catch(e) {
                       console.log(this.responseText);
                       return;
                   }
               }
               FlowEmbed.fetchInitializerKeys({hash_key, (optional)api_host: EMBED_API_ENDPOINT }, (err, embed) => {
                   if(err) {
                       try{
                           return showLoginErrorMessage(JSON.parse(err).user.message);
                       } catch(e) {
                           return showLoginErrorMessage(err);
                       }
                   }
                   window.Embed = embed;
                   start(embed);
                   if(typeof cb === "function" ) {
                       return cb(err, embed);
                   } else {
                      embed.on('ready', () => {
                          window.location = "/";
                       })
                   }
               });
           }
           if(this.readyState == 4 && this.status != 200) {
               console.log("Err - ", this.responseText);
           }
        };
        xhttp.open("POST", API_DOMAIN + API_INITIATE_ROUTE, true);
        // Identifer and email can be sent via body, headers as per your requirement.
        xhttp.setRequestHeader('identifier', IDENTIFIER);
        if(USERNAME)
           xhttp.setRequestHeader('consumer_uid', USERNAME);
           xhttp.send();
        }
        

        Error Message The fetchInitializerKeys function throws the following error if the IP address of your API server is not registered with your Embed tenant: You don't have the necessary permissions to perform the specified operation. In the Developer Tools screen in Admin Portal, we can add an IP Range to restrict API servers from accessing tenant information via initializer request. This only works for step 1.

        Initializing Embed SDK using init() function init\(String identifier, String source\_token, String master\_token, String environment, String version , String api\_host, String exhibit\) This function initializes the SDK. It performs a handshake with the API server and checks whether the provided key combination is valid or not. Since the basic communication rules are set by this function, it should always be called before any other function provided by the SDK. Parameter details:
        • identifier: Retrieve the identifier by navigating to Settings > Developer Tools > Identifier** in the Embed Admin Portal.
        • source\_token: Retrieve the source token by navigating to **Settings > Developer Tools > Source Verification Token** in the Embed Admin Portal.
        • master\_token: Retrieve the identifier by navigating to **Settings > Developer Tools > Master Token** in the Embed Admin Portal.
        • environment: sandbox or production
        • version: v2
        • api\_host: domain for API server \(default: null\)
        • exhibit: Set this to 'true' disable the encryption/decryption mechanism.
        Note: Since the client-side JavaScript does not maintain state, you need to initialize the SDK using the init function while reloading or redirecting to any particular page

        Sample Code for initialize SDK

        
        window.Embed = FlowEmbed.init( identifier, source_verification_token, master_token, environment, "v2", null, false);
        //Below is the logout listener code
        	window.Embed.on("logout", function () {
        		logoutUser();
        	});
        
  2. login(String jwt_signed_token)

    This function logs in the user present inside the JWT token.

    Note: To log in the user along with SDK initialization, send a JWT signed string which is encrypted using an API_KEY.
    Code snippet for JWT token generation
    const jsonwebtoken = require('jsonwebtoken')
    
         const API_KEY = <API_KEY> // Settings -> Developer Tools -> API Key
    
          const user = {
    
                   consumer_uid : <username>, // <Any string>
    
                   domain : <tenant domain>,   // Settings -> Developer Tools -> Domain
    
                   plan : '',
    
        time: new Date().getTime()
    
      }
    
    var jwt = jsonwebtoken.sign(user, API_KEY);
    
    
    
    
    
    //Please use hmac256 encryption algorithm
    

    Sample code:

    window.Embed.login(d).then(
    
    () => {
    
    window.location = "/";  // redirect to home page
    	},
    
    	(err) => {
    
    		console.log(err);
    
    		window.location = "/login"; 
    
    	}
    
    );
    
    Tip: plan code can be found under the Plans tab in the Embed Admin portal.
  3. setActive(deployment_uid, Boolean status) - requires login

    This function turns the specified deployment active or inactive based on the value of status.

    Sample Code:
    let el = document.getElementById('#deployment_elemenet_id');
    
    var status = true;
    
    if(el.dataset.active === "true"){ //set active status in dataset of deployment element
    
    status = false;
    
    }
    
    window.Embed.setActive(<deployment_uid> ,status, (res) => {
    
    	if(status)
    
    	el.dataset.active = "true";
    
    	else
    
     el.dataset.active = "false"
    
    
    
     }, (err) => 
    
    {
    
    console.log(err);
    
    })
    
  4. deleteDeployment(deployment_uid) - requires login

    This function deletes the specified deployment from the list of deployments available in the current user's account.

    Sample code:
    window.Embed.deleteDeployment(deployment_uid).then(function (response) {
    
    	showNotification('success','Integration deleted successfully.', 5);
    
    	location.reload(); // To fetch updated deployment records
    
    }, 
    
    function (err) {
    
    	console.log(err);
    
    })
    
  5. getMyIntegrations() - requires login

    This function retrieves a list of all deployments added in the current user's account.

    Note: You can use getMyDeployments() for optimized pagination (sdk-version 2.1.42 and further).
    Sample Code:
    get({skip, limit,  query: {"name" : {"$regex" : search, "$options" : "gmi"}}, fields});
    
    
    
    function get(obj){
    
    	$('#loader-wrapper').show();
    
    	window.Embed.getMyIntegrations({skip: obj.skip || 0, limit : obj.limit || 15, query: obj.query},fields : ['flows']).then(function(res){
    
    		showIntegrations(res.flows);
    
    		viewPagination(res);
    
    		$('#loader-wrapper').hide();
    
    	})  
    
    }
    
  6. getMyDeployments() – requires login (sdk-version: 2.1.42)

    This function retrieves a list of all deployments added in the logged in user’s account.

    Sample Code
    get({limit,  name: {"name" : {"$regex" : search, "$options" : "gmi"}}, fields: [‘flows’], tags: ‘tag1’, next_sort_date: ‘2022-10-11T10:38:20.237Z’});
    
    
    
    function get(obj){
    
    	$('#loader-wrapper').show();
    
    	window.Embed.getMyDeployments({limit : obj.limit || 15, query: obj.query}, fields : obj.fields, tags: obj.tags, next_sort_date: obj.next_sort_date)
    
    	.then(function(res){
    
    		showIntegrations(res.flows);
    
    		viewPagination(res);
    
    		$('#loader-wrapper').hide();
    
    	})  
    
    }
    
  7. getConnectors()

    This function retrieves a list of connectors/services from the set of available solutions. The Response object contains connector/service name, icon, title, and solutions_count.

    Sample Code:
    window.Embed.getConnectors().then((resp)=>{
    
    	var divs = [];
    
    	for(var i = 0; i < resp.length; i++){
    
    		var a = resp[i];
    
    		if(a.name === "developertools")
    
    		continue;
    
    		if(a.name === "devtools-logger")
    
    		continue;
    
    		var str = '<div data-name="'+a.title+'" class="servicename col-2 center-align mb-30">' +
    
            '<div class="row">' +
    
                '<div class="service-link">'+
    
                    '<a href="/solutions/' + a.name +'" class="mbxl service-icon">'+ window.Embed.getIcon(a,90) + '</a>' +
    
                '</div>'+
    
                '<div class="action-details">' +
    
                    '<a href="/solutions/' + a.name + '" class="action-name block"><span class="action-name-search">'+ a.title+ '</span></a>' +
    
                    '</div> </div> </div>';
    
    				divs.push(str);
    
    	}
    
    	divs = divs.join("");
    
    	var list_content = document.querySelector("#connector-list")
    
    	list_content.innerHTML += divs;
    
    	$('#loader-wrapper').hide(); 
    
    },(err)=>{
    
    	console.log(err);
    
    })
    
  8. getTemplatesByConnector(String connector_name, [String field_name1, String field_name2](optional), String solution_type(optional))

    This function retrieves a list of all active solutions associated with the specified connector/service. The solution type can be webhook or default.

    Sample Code:
    let connector = ""; // Use value of `name` key of response of getConnector function.
    
    let fields = ["version", "is_head", "published", "action_icons", "sandbox_version", "trigger_icon", "name", "published_on", "uid", "context", "environment", "custom_connector_exists"]
    
    window.Embed.getTemplatesByConnector(connector, fields).then((resp)=>{
    
    	$('#loader-wrapper').hide();
    
    	var list_content = document.querySelector("#solutions-list")
    
    	let path = window.location.pathname;
    
        for(var i = 0; i < resp.length; i++){
    
            
    
            var a = resp[i];
    
            var li = document.createElement('li');
    
            li.classList.add('inline-block');
    
            li.classList.add('clearfix');
    
            li.classList.add('col-12');
    
            li.classList.add('left');
    
            li.classList.add('ptm');
    
            li.classList.add('pbm');
    
            
    
            var solutionName = document.createElement('p');
    
            solutionName.classList.add('left');
    
            solutionName.classList.add('col-6');
    
            solutionName.classList.add('ellipsis');
    
            solutionName.classList.add('prl');
    
            solutionName.innerText = a.name;
    
            solutionName.title = a.name;
    
    
    
            var icon = document.createElement('div');
    
            icon.classList.add("left");
    
            icon.classList.add("col-4");
    
            icon.classList.add("content-limit");
    
            icon.innerHTML = window.Embed.getIcon(a,30);
    
    
    
            var add = document.createElement('a');
    
            add.classList.add('btn');
    
            add.classList.add('btn-primary');
    
            add.classList.add('add-button');
    
            add.classList.add('right');
    
            add.innerText = 'Add';
    
            add.id = i;
    
            add.dataset.path = path+'/'+a.uid
    
    
    
            add.addEventListener('click',  (e) => redirectToFormPage(e.target.dataset.path));
    
    
    
            if(isLoggedIn()) {
    
                li.append(solutionName);
    
                li.append(icon);
    
                li.append(add);  // Only loggedin use can view the form
    
            } else{
    
                li.append(solutionName);
    
                li.append(icon);
    
            }
    
        }
    
    },(err)=>{
    
    console.log(err);})
    
  9. getTemplates()

    Retrieves a list of all active solutions available to the user. Users can pass specific field names they want to fetch along with the solution, in the form of an array of strings.

    Sample Code:
    fields = ["version", "is_head", "published", "action_icons", "sandbox_version", "trigger_icon", "name", "published_on", "uid", "context", "environment", "custom_connector_exists"]
    
    	window.Embed.getTemplates(fields).then((resp) => {
    
    	listTemplates(resp);
    
    }, (err)= {
    
    	console.log(err);
    
    })
    
  10. getDeploymentIcons(Object deployment, String|Number size)

    This function retrieves a strip of HTML containing icons of trigger and actions used in the specified deployment. This function is especially useful while listing solutions/deployments. Icon size can be of 16/24/28/30/36/40/45/48/50/64/70/80/90/96/128 pixels.

    Sample Code:
    var deployment_obj = {trigger_icon: “webhook”, action_icons: [“trello”,”asana”]};
    
    var size = 30;
    
    var element = window.Embed.getDeploymentIcons(deployment_obj, size);
    
    Add above element in DOM.
    
  11. getIcon(Object obj|String icon, Number size)

    This function retrieves icon for the specified object. This function is especially useful for displaying connector icons. Icon size can be of 16/24/28/30/36/40/45/48/50/64/70/80/90/96/128 pixels.

    Sample Code:
    var icon = “trello”
    
    var obj = {icon: “trello”};
    
    var size = 30;
    
    var element = window.Embed.getIcon(icon, size);
    
    Add above element in DOM.
    
  12. logout() - requires login

    This function logs out the user. After successful logout, the 'logout' event is raised which can be caught by the client JavaScript to perform other tasks. Event listeners can be attached and removed by using 'on' and 'off' methods. On logout, all the local storage and event listeners are removed.

    Once user clicks on the Logout button, perform below logout operation using SDK’s logout function.

    function embedLogout() {
    
    	window.Embed.logout();
    
    }
    
  13. getAuths(provider, searchPattern) - requires login

    This function fetches all auths associated with the currently logged-in user for the specified provider. There are two function parameters required, first is provider which is mandatory and second is searchObject which is optional. For searchObject, we can fetch objects by label of auth.

    Note: This function can be in custom form-render to fetch the user's auth based on the provider and show it as options in the select box.
    Sample Code:
    var provider = “asana”;
    
    var searchObject = {“label”: “Asana_12345687”}; // This is optional
    
    Embed.getAuths(provider , searchObject ).then((resp) => {
    
    	listUserAuthOptions(resp);
    
    },
    
    (err)=> {
    
    console.log(err);
    
    })
    
  14. validateToken()

    This function checks whether the user is logged in or not. This function calls the ‘logout’ event internally if the session of the user is invalid. Make sure that you have logout functionality handled in your application.

    Sample Code:
    window.Embed.on('ready', () => {
    
    	window.Embed.validateToken();
    
    })
    
  15. getDeploymentStats(Array deployments, Object params(optional))

    This function retrieves the number of executions for some or all deployments. Deployments should be passed as an array. If the array is left blank, it returns the execution statistics for all deployments. Optionally, 'params' can be used to enable pagination functionality with the 'skip' and 'limit' properties.

    Sample Code:
    var deployment = [ 'deployment_uid1', 'deployment_uid2' ... ]; // deployment array can be empty
    
    var params = {“skip”: 0,”limit”:15}
    
    window.Embed.getDeploymentStats(deployment, params).then((resp)=> {
    
    	//resp is array of object which has following keys - flow_uid, title, runcount
    
    	listDeploymentStats(resp);
    
    }, (err)=> 
    
    {
    
    console.log(err);
    
    })
    
  16. getConsumerUsage()

    This function retrieves the total number of executions that have been done by the user. If the tenant is transaction based then skip the available key as it won’t matter.

    Sample Code:
    window.Embed.getConsumerUsage().then((res)=> {
    
    	document.querySelector("#used-usage").innerHTML = "Used : " + res.used_credits;
    
    	if(res.available &&  !res.is_transaction_tenant) {
    
        document.querySelector("#available-usage").innerHTML = "Available : " + res.available;
    
    	}
    
    	document.querySelector("#plan-type").innerHTML = "Plan Name : " + res.plan_name;
    
    }, 
    
    (err)=> {
    
    console.log(err);
    
    })
    
  17. getConsumerUsageByDate(startDate, endDate(optional))

    This function retrieves the total number of executions that were performed by the user for a specific date frame.

    Sample Code:
    var startDate = "YYYY-MM-DD"; // optional
    
    var endDate = "YYYY-MM-DD"; // optional
    
    window.Embed.getConsumerUsageByDate(startDate, endDate).then((resp)=> {
    
    	listExecutions(resp)
    
    }, 
    
    (err)=> {
    
    console.log(err);
    
    })
    
  18. getExecutions(Object params)

    This function retrieves all executions with respect to the consumer/user. 'params' can be used to enable pagination functionality with the 'skip' and 'limit' properties.

    var params = { limit: 15, skip: 0 }
    
    window.Embed.getExecutions(params).then(function(res){
    
    	showExecutionLogs(res.objects);
    
    	viewPagination(res);
    
    }) 
    
    To filter execution logs:

    You can filter out specific execution logs based on date & time, integration name, and execution status. This is achieved by setting parameters (to_date, from_date, deployment_flow_uid, execution_status) respectively.

    getExecutionLogs(obj):

    Called: On initial render and by filterData( ) i.e. when Apply Filter button is clicked.

    Parameter: obj containing {skip, limit, from_date, to_date, deployment_flow_uid, execution_status} keys depending on the filter selected.

    Note:
    • It is not mandatory to provide all keys present in the obj definition. You can provide keys relevant to your search.

    • If 'to_date' key is provided, it’s necessary to provide 'from_date' as well and vice versa.

    Functionality: Clears previous execution logs (if any) Loader util response Get filterObj i.e. {to_date, from_date, deployment_flow_uid, execution_status} from obj if key is passed. Get response from getExecutions(obj) and populate the response.

    function getExecutionLogs(obj) {
    
     // clear previous execution logs
    
     // get deployment_flow_uid, execution_status, from_date, to_date from respective dropdown
    
     let filterObj = getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj)
    
     //calling API to get execution-logs as res
    
     window.Embed.getExecutions({
    
     skip: obj.skip || 0,
    
     limit: obj.limit || 15,
    
     ...filterObj,
    
     }).then(function (res) {
    
     showExecutionLogs(res.objects)
    
     enableApplyResetBtn()
    
     viewPagination(res, filterObj)
    
     })
    
     }
    

    getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj):

    Called: By getExecutionLogs(obj)

    Parameter: obj containing {skip, limit, from_date, to_date, deployment_flow_uid, execution_status} It is not mandatory to provide all keys present in the obj definition. You can provide keys relevant to your search.

    Functionality: Returns an obj {deployment_flow_uid, execution_status, from_date, to_date} if key exists, by calling returnKeyValueObjIfKeyExists(obj, key)

    Sample Code
    function getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj){
    
      let tempObj;
    
      tempObj = {
    
        ...(returnKeyValueObjIfKeyExists(obj,"deployment_flow_uid")),
    
        ...(returnKeyValueObjIfKeyExists(obj,"execution_status")),
    
        ...(returnKeyValueObjIfKeyExists(obj,"from_date")),
    
        ...(returnKeyValueObjIfKeyExists(obj,"to_date")),
    
     }
    
     return tempObj
    
    }
    

    returnKeyValueObjIfKeyExists(obj, key):

    Called: By getDeploymentFlowUid_ExecutionStatus_FromDate_ToDate(obj)

    Parameter: {obj, key}

    Functionality: Returns an object with key-value pair if key exists in the obj.

    Sample Code

    function returnKeyValueObjIfKeyExists(obj, key) {
    
       if (obj[key] !== undefined)
    
       return {[key]: obj[key]};
    
     }
    
  19. getExecutionLogs({bill_uid, limit, skip})

    This function retrieves the execution logs of particular execution. Bill uid can be found in response of getExecutions function.

    Sample Code:

    var bill_uid="bill_uid1"   
    
    
    
    	window.Embed.getExecutionLogs({logUid:bill_uid, limit:Number(limit), skip:Number(skip)}).then(function(res) {
    
        var userstream_logs = res.objects.filter((log) => { return log.type != 'bill' });
    
        var activityLog = userstream_logs ? userstream_logs.sort() : [];
    
        var isLoading = true;   
    
        var modal = document.querySelector("#activity-logs-modal");
    
        var title = `Execution Logs: ${htmlEncode(obj.flow_name)}`;
    
        var modalHeader = document.querySelector('.modal-title');
    
        modalHeader.innerText = title;
    
        // modal.innerHTML += "<div class='modal-container'><div class='modal-header pbm'><h3>Execution Logs: "+obj.flow_name+"</h3></div><div class='modal-body'><table class='logs-table'><thead><th class='width-45'>Action</th><th>Start</th><th>End</th></thead><tbody id='logs-modal-body'></tbody></table></div><div class='modal-footer clearfix mtxl'><button class='btn secondary-btn' onclick='closeLogsModal()'>Close</button></div></div>";
    
        if(activityLog && activityLog.length){
    
            for(var i=0; i<activityLog.length; i++){
    
                var start_date = new Date(activityLog[i].time_stamp);
    
                start_date = start_date.toLocaleString().split(",");
    
                var end_date = new Date(activityLog[i].stop_time_stamp);
    
                end_date = end_date.toLocaleString().split(",");
    
                var message = activityLog[i].error ? activityLog[i].message_exp : activityLog[i].activity_name;
    
                logsRow.innerHTML += "<tr><td class='width-45'>"+message+"</td><td class='center-align'>"+start_date[1].trim()+"</td><td class='center-align'>"+end_date[1].trim()+"</td></tr>";
    
                isLoading = true;
    
            }           
    
        }else{
    
            logsRow.innerHTML += "<tr><td colspan='3' class='center-align'>No Logs</td></tr>";
    
            isLoading = true;
    
        }
    
        if(res.total > 200){
    
            viewPagination(res,'fromGetDetailedExecutionLogs', obj);
    
        }
    
        if(isLoading){
    
            setTimeout(function(){
    
                modal.style.display = "block";
    
                viewLogElement.style.pointerEvents = 'auto';
    
            }, 1000);
    
        }
    
    }, (err)=> {
    
        viewLogElement.style.pointerEvents = 'auto';
    
        console.log(err);
    
    })
    
  20. createProject()If you are using the Embed SDK version 2.1.21 or above, you need not use this function. The Embed SDK automatically executes this function on your behalf whenever required.

    This function creates a project for your tenant account. Before initializing the solution use this function to create a project. If the workflow contains a custom connector then window.Embed.createProject(obj) requires the following object to be passed while calling the function. {custom_connector_exists, solution_uid, solution_version}

    Sample code for this function:

    function createProject(link, solution) {
    
    localStorage.removeItem('project')
    
    var projectCreatePayload = {};
    
    if(solution && solution.hasOwnProperty("custom_connector_exists") && solution.uid && solution.version) {
    
       projectCreatePayload = {
    
           custom_connector_exists : solution.custom_connector_exists,
    
           solution_uid : solution.uid,
    
           solution_version : solution.version
    
       }
    
    
    
    }
    
    window.Embed.createProject(projectCreatePayload).then((res) => {
    
       window.location = link;
    
    }, (err) => {
    
       console.log(err);
    
    })
    
    }
    
  21. getSolutionsByBotId()

    This function retrieves all active solutions added inside a bot.

  22. getBotTokenByBotId

    This function retrieves bot information.

  23. getConsumer(string consumer_uid)

    This function retrieves logged in consumer’s information.

    Sample Code:

    var consumer_uid = 'consumer_uid1'; // Default value is `me`
    
    Embed.getConsumer(consumer_uid).then((resp) => {
    
    	var consumer_object = resp
    
    }, (err) => {
    
    console.log(err);})
    
  24. getSolution(solution_uid)

    This function retrieves active solution or template object.

    Sample Code:

    var solution_uid = "solution_uid1";
    
    Embed.getSolution(solution_uid).then((resp) => {
    
    	var solution_object = resp;
    
    }, (err) => {
    
    console.log(err);})
    
    Solution object looks like this:
    
    {
    
    action_icons: ['wunderlist']
    
    context: "sandbox"
    
    created_at: "2019-09-23T08:08:17.278Z"
    
    environment: {project_params: Array(3)}
    
    name: "wunderlist solution"
    
    origin: "fl1bbbb41190879222069006"
    
    output: []
    
    published: true
    
    published_on: "2019-09-23T08:08:17.268Z"
    
    trigger_icon: "wunderlist"
    
    uid: "fl281b3493f53286088c6e471"
    
    updated_at: "2020-06-30T14:02:28.694Z"
    
    version: 2
    
    }
    
  25. getTenant(provider)

    This function checks whether OAuth is present or not with the specified provider. If OAuth is not present for the specified provider, then the function returns {tid: "builtio"} otherwise it returns metadata of the OAuth. Whenever you use addAuth function, this function checks internally if there is an oauth present with a given provider or not.

    Sample Code:

    window.Embed.getTenant(provider, identifier ).then((resp) => {
    
    	var data = resp;
    
    	if(data && data.hasOwnProperty('t') && data.t != "builtio"){\
    
        You can continue with tenant oauth creation process eg. (Embed.createUserTenantOauth() function);  		      
    
    	}else{
    
        You can continue with auth process eg. (Embed.addAuth() function)
    
    	}
    
    }, (err) => {
    
    	console.log(err);
    
    })
    
  26. performOperation(operation_obj)

    To access this function, you need to enable the Bots feature for your tenant. This is a custom method to perform several operations.

  27. createUserTenantOauth(oauth_obj)

    This function allows users to create a new OAuth for a tenant.

    Sample Code

    var obj = {
    
    	provider : provider,
    
    	identifier: domain, // This is depend on connector ex. (for servicenow connector, identifier will be the domain of the servicenow instance)
    
    	description : "description",
    
    	params : {
    
    		client_id : clientId,
    
    		client_secret : clientSecret,
    
    		redirect_uri : redirectURI // format -> `${authHost}/oauth/${provider}/tenant/${tenant_uid}/env/${env_uid}/identifier/${domain}/return`
    
    		... //other keys are depened on connector
    
    	}
    
    }
    
    
    
    window.Embed.createUserTenantOauth(obj).then((resp) => {
    
    	// once you get response of tenant Oauth creation, you can continue with auth process eg. (Embed.addAuth() function)
    
    }, (err) => {
    
    	console.log(err);
    
    })
    
  28. setConnectorFields (payload)

    To access this function, you need to enable the Bots feature for your tenant. This function is used to store metadata of the user.

  29. getConnectorFields (payload)

    To access this function, you need to enable the Bots feature for your tenant. This function is used to fetch metadata of the user.

  30. getAuthtoken()

    This function retrieves logged in user's auth token. If the user is not logged in, then the function returns 'undefined'.

    Sample Code:

    var authtoken = window.Embed.getAuthtoken();
    
  31. createErrorLog(Object)

    This function adds custom error logs.

    Object must contain operation, module, and error key where-

    • operation - READ/WRITE/UPDATE/DELETE
    • module - any module (ex. Solution, Deployment)
    • error - Error message or object.

    Sample Code:

    Embed.createErrorLog({"operation": "READ", "module" : "CustomError", "error" : {“message” :"error encountered"}});
    
  32. getConsumerAuths({label, limit, next_sort_date, prev_sort_date}) (sdk-version: 2.1.41)

    This function retrieves the list of authorizations along with the following properties associated with them: {uid, project_uid, label, provider, method}

    Parameters

    • label: To search auth (partial/complete) (optional parameter)
    • limit: Number of authorizations to be fetched
    • next_sort_date/ prev_sort_date: To fetch next and previous authorization list for pagination respectively

    Sample Code

    function getConsumerAuths() {
    
    let name = "Marketo123456";
    
    let next_sort_date = "2022-10-11T10:38:20.237Z";
    
    var $element = document.getElementById('auth-list');
    
    window.Embed.getConsumerAuths({label: name, limit:15, next_sort_date}).then((resp) => {
    
        $element.innerHTML = '';
    
        let list = resp.items;
    
        listConsumerAuths(list);
    
        viewPagination(resp);
    
     }, (err) => {
    
        console.log("Error while fetching userauths", err);
    
     })
    
     }
    
  33. getConsumerConnections({label, limit, next_sort_date, prev_sort_date}) (sdk-version: 2.1.41)

    This function retrieves a list of connections along with the following properties associated with them: {uid, project_uid, label, provider, method}.

    Parameters

    • label: To search auth (partial/complete) (optional parameter)
    • limit: Number of connections to be fetched
    • next_sort_date/ prev_sort_date: To fetch next or previous connection list for pagination respectively

    Sample Code

    function getConsumerConnections() {
    
    let name = "Pagerduty123456";
    
    let next_sort_date = "2022-10-11T10:38:20.237Z";
    
    window.Embed.getConsumerConnections({label: name, limit:15, next_sort_date}).then((resp) => {
    
        let list = resp.items;
    
        listConsumerAuths(list);
    
        viewPagination(resp)
    
    }, (err) => {
    
        console.log("Error while fetching userauths", err);
    
    })
    
    }
    
  34. updateAuth({auth_uid, project_uid, label, provider, customAuthFormRender, scopeScreen, closeScopeScreen, method}, cb) (sdk-version: 2.1.41)

    This function updates the authorization associated with the specified auth_id.

    Parameters

    • auth_uid, project_uid, label, provider, method: These keys can be obtained using the getConsumerAuths() function
    • customAuthFormRender(): Renders custom authorization modal using renderForn()
    • scopeScreen(scopes): Creates modal for updating authorization with the provided scopes
    • closeScopeScreen(scopeElement): Closes modal created by scopeScreen() for the provided scope element
    • cb: Callback function

    Sample Code

    function updateAuth() {
    
    let auth_uid = 'au12345fbace123b1234d91c6cd698f5726dfdb';
    
    let project_uid = 'fl1a1f1cc12345aaa1d1ad12';
    
    let label = '"Trello_0123456789';
    
    let provider = 'trello';
    
    
    
    if( !auth_uid || !project_uid || !label || !provider) {
    
        console.log("Update auth parameter missing");
    
        return;
    
    }
    
    
    
    // Custom form to update auth depending on the schema
    
    function customAuthFormRender(cs, cb) {
    
        try {
    
          custom_auth_schema = JSON.parse(cs);
    
        } catch (e) {
    
        console.error("Custom auth schema is invalid.");
    
        return;
    
        }
    
        var $formElement = document.querySelector("#update_auth_form");
    
        window.Embed.renderForm($formElement, {schema: custom_auth_schema, value:{}, isCustomAuth: true});
    
        var cbSuccess = (data) => {
    
            let updateAuthModal = document.getElementById("update-auth-title-modal");
    
            updateAuthModal.innerHTML='';
    
            $formElement.innerHTML = '';
    
            window.Embed.off('form.submit', cbSuccess);
    
            return cb(data);
    
        };
    
        window.Embed.on('form.submit', cbSuccess)
    
        var cbFailed = () => {
    
            $formElement.innerHTML = '';
    
            window.Embed.off('form.cancel', cbFailed);
    
        } 
    
        window.Embed.on('form.cancel', cbFailed );
    
    }
    
    
    
    window.Embed.updateAuth({auth_uid, project_uid, label, provider, customAuthFormRender, scopeScreen, closeScopeScreen, method}, (err, resp) => {
    
        if(err) {
    
            showNotification('error', 'Auth update failed', 5);
    
        }
    
        if(resp) {
    
            showNotification('success', 'Auth updated successfully', 5);
    
            let $input = document.getElementById('auth_label');
    
            ($input) && getConsumerAuths($input.value);
    
        }
    
        closeUpdateAuthTitle();
    
    })
    
    }
    
  35. updateConnection({data, connection_uid, provider, project_uid }) (sdk-version: 2.1.41)

    This function updates the connection or account associated with the specified connection_uid. It verifies the data provided for connection before updation.

    Parameters

    • {connection_uid, provider, project_uid}: These keys can be obtained from using getConsumerAuths() function
    • data: Data can be obtained by using the render_IC_connection_form() or the renderForm() function.

    Sample Code

    // Create modal to update connection
    
    async function updateConnectionForm() {
    
    let auth_uid = "uconn123f851bfc4eb123a6148c123dc124534d1a7e97";
    
    let label = "Pagerduty_Connection_0123456789";
    
     let provider= "pagerduty_-1abcAZqw";
    
     let project_uid="fle3a9876a123ca1cb12345ddea5e9f6f";
    
    
    
    let connectorSchema = await Embed.getConnectorSchema(provider);
    
    if(connectorSchema && connectorSchema.form_schema) {
    
        let schema = connectorSchema.form_schema;
    
    	// check if the provider is CloudStream Connector
    
        var isIC = isICConnector(provider);    
    
        try{
    
            if(isIC){
    
                schema = schema[0].fields;
    
            } else {
    
                schema = JSON.parse(schema);
    
            }
    
        } catch(e) { 
    
            console.log('Error while parsing connection schema - ',schema); 
    
            return null;
    
        };
    
        // Disable label property
    
        if(isIC) {
    
            schema[0].defaultValue = label;
    
            schema[0].propertyValue = label;
    
            schema[0].disabled = true;
    
        } else {
    
            schema.properties.label.disabled = true;
    
        }
    
        var $formElement = document.querySelector("#update_auth_form");
    
        // ================== Add IC form render function
    
        if(isIC) {
    
            render_IC_connection_form(schema, $formElement, (data) => {
    
                $formElement.innerHTML = '';
    
                $formElement.style.display = "none";
    
                return updateConnection({data: data, project_uid, connection_uid: auth_uid, provider});
    
                
    
            });
    
        } else {
    
            window.Embed.renderForm($formElement, {schema, value:{label}, isConnection: true});
    
            var cbSuccess =  (data) => {
    
                $formElement.innerHTML = '';
    
                $formElement.style.display = "none";
    
                removeEmbedFormListner();
    
                return updateConnection({data: data.data, project_uid, connection_uid: auth_uid, provider});
    
            };
    
          
    
            window.Embed.on('form.submit',cbSuccess)
    
            var cbFailed = () => {
    
                $formElement.innerHTML = '';
    
                removeEmbedFormListner();
    
            };
    
            function removeEmbedFormListner() {
    
                window.Embed.off('form.submit', cbSuccess);
    
                window.Embed.off('form.cancel', cbFailed);
    
            }
    
            window.Embed.on('form.cancel', cbFailed);
    
        }
    
    	}
    
    }
    
    
    
    // Verify connection update success or failure
    
    	function updateConnection({data, connection_uid, provider, project_uid }) {
    
    	window.Embed.updateConnection({data, project_uid, connection_uid, provider})
    
    	.then(resp) => {
    
            if(resp) 
    
                showNotification('success', 'Connection updated successfully', 5);
    
     		else 
    
                showNotification('error', 'Connection update failed', 5);
    
    	}, (err) => {
    
            console.log("Connection update error - ", err);
    
            showNotification('error', 'Connection update failed', 5);
    
    	}
    
    }
    
  36. getDeploymentTags() (sdk-version: 2.1.44)

    This function retrieves the tags associated with all deployments.

    Sample Code

    window.Embed.getDeploymentTags().then((res) => {
    
    	let deploymentTagsElement = document.getElementById("deployment_tags");
    
    	// id of <select> tag used to select deployment/ integration tags
    
    	if(res && res.length) {
    
    	res.map((x) => {
    
    		let option = document.createElement("option");
    
    		option.value = x.name;
    
    		option.innerText = x.name;
    
    		deploymentTagsElement.appendChild(option);
    
    		})
    
    	}
    
    })
    
  37. restartDeployment() (sdk-version: 2.1.49)

    This function restarts a deployment when it fails, time outs, or stops. To use this function, you must first enable restart for the particular deployment (from solution.setRestartDeployment())

    Parameter

    • uid: UID of the deployment to be restarted (can be obtained from getExecutions())

    Sample Code

    let deploymentUID = '123456abcd' // can be obtained from Embed.getExecutions()
    
    window.Embed.restartDeployment({uid:deploymentUID}).then(function(res){
    
    	window.location.reload();
    
    } ,(err) =>{
    
    	console.log(err);
    
    })
    
  38. bulkRestartDeployment() (sdk-version: 2.1.67)

    This function restarts multiple deployments when they fail, time out, or stop. To use this function, you must first enable restart for each deployment (can be obtained from solution.setRestartDeployment()).

    Parameter

    • uids: Array of UIDs for the deployments to be restarted (can be obtained from getExecutions())

    Sample Code

    let deploymentUIDs = ['123456abcd', ‘9876qwert’] // can be obtained from Embed.getExecutions() 
    
    window.Embed.bulkRestartDeployment({uids:deploymentUIDs}).then(function(res){ 
    
    window.location.reload(); 
    
    } ,(err) =>{ 
    
    	console.log(err); 
    
    }) 
    
  39. resumeDeployment({flow_uid, uid}) (sdk-version: 2.1.67)

    This function resumes a deployment when it stops. To use this function, you must first enable solution.setRestartDeployment() function for the deployment.

    Parameter

    • flow_uid: Flow UID of the deployment to be resumed (can be obtained from getExecutions())

    • uid: UID of the deployment to be resumed (can be obtained from getExecutions())

    Sample Code

    let deploymentFlowUID = '98765qwert' // can be obtained from Embed.getExecutions() 
    
    let deploymentUID = '123456abcd' // can be obtained from Embed.getExecutions() \
    
    window.Embed.resumeDeployment({flow_uid:deploymentFlowUID, uid:deploymentUID}).then(function(res){ 
    
    window.location.reload(); 
    
    } ,(err) =>{ 
    
    	console.log(err); 
    
    })