Working with multiple clients credentials

Hi everyone, I have a backend application that will be used by two different organizations.
Is there a way to manage multiple clients logged in?

My approach was to write a platform.js file as such:

const platformClient = require('purecloud-platform-client-v2');

module.exports = class Platform {
		constructor(credential) {
			this.clientId = credential.clientId;
			this.clientSecret = credential.clientSecret;
			this.client = platformClient.ApiClient.instance
		}
		login() {
			this.client.setEnvironment("mypurecloud.de");
			return this.client.loginClientCredentialsGrant(this.clientId,this.clientSecret)
		}
		getDatatableRows(datatableId, opts) {
			let apiInstance = new platformClient.ArchitectApi();
			return apiInstance.getFlowsDatatableRows(datatableId, opts)
		}
	}

a PlatformFactory.js:

const Platform = require('./Platform')

class PlatformFactory {
	createClient(credential) {
		return new Platform(credential)
	}
}

module.exports = new PlatformFactory();

and finally in index.js

const client1 = PlatformFactory.createClient(cred1)
const client2 = PlatformFactory.createClient(cred2)

client1.login().then(res => console.log('1 OK')).catch(e => console.log(e))
client2.login().then(res => console.log('2 OK')).catch(e => console.log(e))
    
function getTables() {
  
  let opts = {pageNumber:1,pageSize:500,showbrief:false};

  client1.getDatatableRows(dt1, opts)
  .then(tables => console.log(tables.entities.length))
  .catch(err => console.log(err.text))
  
  client2.getDatatableRows(dt2, opts)
  .then(tables => console.log(tables.entities.length))
  .catch(err => console.log(err.text))
}

I would like to avoid to login at each request hence storing the clients into different variables seemed like a good idea, but the two are obviously conflicting with each other. Do you have any suggestion?

Hello,

ApiClient (platformClient.ApiClient) is a singleton class.

But you should be able to set the access token before calling an API endpoint/method.

The loginClientCredentialsGrant method returns a credentials object (so you can get the access token, and save it somewhere).

apiClient.loginClientCredentialsGrant(clientGrant_id, clientGrant_secret)
    .then((creds) => {
        console.log('Logged In with access token: ' + creds.accessToken);
        ...
    })
    // Error Handling
    .catch(e => console.log(e));

And you can then set your access token (before calling a Platform API endpoint) with apiClient.setAccessToken(your_token).

Regards,

1 Like

This topic was automatically closed 31 days after the last reply. New replies are no longer allowed.