Classes

This document contains the documentation for the classes available in the Toolbelt.


CsdsClient

core-functions-toolbelt / CsdsClient

Implements

Constructors

Constructor

new CsdsClient(ttlInSeconds, accountId, lastCacheTimestamp, httpClient): CsdsClient

Parameters
ttlInSeconds

number = 600

TTL of the domains cache in seconds

accountId

string = process.env.X_LIVEPERSON_BRAND_ID

lastCacheTimestamp

number = 0

httpClient

{(input, init?): Promise<Response>; (input, init?): Promise<Response>; }

Returns

CsdsClient

Methods

get()

get(service): Promise<string>

Get the host for a CSDS service name. The CsdsClient will get all hosts for the account and cache them as configured in ttInSeconds (see constructor).

Parameters
service

string

Returns

Promise<string>

Implementation of

ICsdsClient.get


getAll()

getAll(): Promise<Record<string, string>[]>

Returns all the available services domains per account

Returns

Promise<Record<string, string>[]>

Implementation of

ICsdsClient.getAll


ToolBeltError

Extends

  • Error

Constructors

Constructor

new ToolBeltError(component, code, message): ToolBeltError

Parameters
component

string = 'General'

code

string

message

string

Returns

ToolBeltError

Overrides

Error.constructor

Properties

code

code: string


component

component: string = 'General'


message

message: string

Inherited from

Error.message


name

name: string

Inherited from

Error.name


stack?

optional stack: string

Inherited from

Error.stack


prepareStackTrace()?

static optional prepareStackTrace: (err, stackTraces) => any

Optional override for formatting stack traces

Parameters
err

Error

stackTraces

CallSite[]

Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from

Error.prepareStackTrace


stackTraceLimit

static stackTraceLimit: number

Inherited from

Error.stackTraceLimit

Methods

captureStackTrace()

static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters
targetObject

object

constructorOpt?

Function

Returns

void

Inherited from

Error.captureStackTrace


Toolbelt

Provides easy access to commonly used resources such as the secret store or a wrapped lpclient.

Basic example

 import { Toolbelt } from 'core-functions-toolbelt';
 const secretClient = Toolbelt.SecretClient();
 const lpClient = Toolbelt.LpClient();
 const gDPRUtil = Toolbelt.GDPRUtil();
 const sDEUtil = Toolbelt.SDEUtil();
 const mTLSClient = Toolbelt.MTLSClient({ cert:'sample', key:'sample', ca:'sample' });
 const contextServiceClient = Toolbelt.ContextServiceClient({ accountId: '1234', apiKey: '5678' });
 const orchestratorClient = Toolbelt.OrchestratorClient()
 const client = Toolbelt.LPMtlsClient();
 const sFClient = Toolbelt.SFClient();
 const csdsClient = Toolbelt.CsdsClient();

Constructors

Constructor

new Toolbelt(): Toolbelt

Returns

Toolbelt

Methods

ContextServiceClient()

static ContextServiceClient(apiKey): IFaaSContextServiceClient

Returns a Context Service Client which can be used to interact with the Context Session Store V1. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#ifaascontextserviceclient)

Parameters
apiKey

string

API key for the Context Session Store.

Basic example

 import { Toolbelt } from 'core-functions-toolbelt';
 const contextApikey = "<your_api_key"; // Please add your own key
 const contextClient = Toolbelt.ContextServiceClient(contextApikey);
 try{
     const config = { accountId: '1234', apiKey: '5678' }
     const client = new contextServiceClient(config);
     // create namespace
     await client.createNamespace('samplenamespace');
     // get list of all namespaces
     const nameSpaces = await client.getListOfNamespaces();
     // set properties in namespace
     await client.setPropertiesInNamespace('samplenamespace', 'sample');
     // update properties in namespace
     await client.updatePropertiesInNamespace('samplenamespace', 'sample');
     // delete namespace
     await client.deleteNamespace('sampleNameSpace');
     // get all properties in a session, note: sessionId is optional, if not used default session will be used
     await client.getAllPropertiesInSession('samplenamespace', 'sessionId');
     // get selected properties in a session, note: sessionId is optional, if not used default session will be used
     await client.getSelectedPropertiesInSession('samplenamespace', ['sampleone', 'sampletwo'], 'sessionId');
     // get property in Session, note: sessionId is optional, if not used default session will be used
     await client.getPropertyInSession'samplenamespace', 'samplepropertyname', 'sessionId');
     // update property in Session, note: sessionId is optional, if not used default session will be used
     await client.deletePropertyInSession('samplenamespace', 'samplepropertyname', 'sessionId');
     // get list of all sessions
     await client.getListOfSessions('samplenamespace');
     // delete session
     await client.deleteSession('samplenamespace', 'sessionId');
 } catch (error){
     console.error(`Received following error message: ${error.message}`);
 }
Returns

IFaaSContextServiceClient


ConversationUtil()

static ConversationUtil(): IConversationUtil

Returns a Conversation Util, which can be used to retrieve conversations and execute operations upon them. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-classes.html#conversationutil)

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';
 const conversationUtil = Toolbelt.ConversationUtil();
 try{
     const conversationId = 'de0ab208-f2e1-4901-9797-a0a31cb798eb';
     const conversation = await conversationUtil.getConversationById(conversationId);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

IConversationUtil


CsdsClient()

static CsdsClient(): CsdsClient

Returns a CSDS client that allows you to discover the domains of liveperson services associated with your account. Be aware that domains are cached for 10 minutes.

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';
 const csdsClient = Toolbelt.CsdsClient();
 try {
     const domain = await csdsClient.get("askMaven");
     const allDomains = await csdsClient.getAll();
 } catch (error){
    console.error(`Received following error message: ${error.message}`);
 }
Returns

CsdsClient


GDPRUtil()

static GDPRUtil(): IGDPRUtil

Returns GDPR Util client, which can be used for GDPR related functionality such as replacing files of a conversation. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#igdprutil)

Basic example

 import { Toolbelt } from 'core-functions-toolbelt';
 const gDPRUtilClient = Toolbelt.GDPRUtil();
 try{
     const conversationId = "de0ab208-f2e1-4901-9797-a0a31cb798eb";
     const credentials ={
            username: "user",
            password: "pass"
      };
     // First, get the conversation in which the image files need to be replaced
     const conversation = await gDPRUtilClient.getConversationById(
         conversationId
     );
     // Default replacement will use a generic image
     let response = await gDPRUtilClient.replaceConversationFiles(conversation, credentials);

     // You can add a custom replacement criteria function based on image path
     const shouldRetryFn = (path) => {
         // add your custom retry criteria based on path. path is a string.
         if (path.startsWith('some_text')) return true;
         return false;
      };
     response = await gDPRUtilClient.replaceConversationFiles(conversation, credentials, shouldRetryFn);

     // You can change the generic image by your custom image
     const file = {
        body: Buffer.from('Your-file', 'base64'),
        contentType: 'image/png',
     };
     response = await gDPRUtilClient.replaceConversationFiles(conversation, credentials, () => true, file);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

IGDPRUtil


LpClient()

static LpClient(): ILpClient

Returns a LivePerson (LP) Client which is a wrapper for the Node Fetch http Client. It simplifies the usage of LivePerson APIs by providing automatic service discovery as well as taking care of the authorization. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-type-aliases.html#ilpclient) The LP service entries comes from liveperson csds service for more information read here (documentation)(liveperson-functions-v2-toolbelt-documentation-enumerations.html#lpservices)

Basic example

 import { Toolbelt, LpServices } from 'core-functions-toolbelt';
 const lpClient = Toolbelt.LpClient();
 try{
     // The same options as those available in the Fetch HTTP client
     const options = {
         method: 'POST',
         headers: {
               'Content-Type': 'application/json',
         },
         body: JSON.stringify({
            conversationId: "077d80a9-7c45-4899-8480-306523868324",
         }),
     };
     response = await lpClient(
         LpServices.MSG_HIST,
         `/messaging_history/api/account/${accountId}/conversations/conversation/search`,
         options
     );
  } catch (error) {
     console.error(`Received following error message: ${error.message}`);
  }
Returns

ILpClient


LPMtlsClient()

static LPMtlsClient(): ILpMtlsClient

Returns a Client for the (LP MTLS)[https://developers.liveperson.com/mtls-overview.html] Service, please be aware that you need to perform the (onboarding)[https://developers.liveperson.com/mtls-mtls-self-service.html] before being able to leverage the client. It will use the provided OAuth2 App Installation credentials to obtain an access token and use that for communication with sentinel. Errors related to LP MTLS or Upstream failing will be thrown as MTLSError and can be differentiated using the MTLSError.code property.

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';

 try{
     const target = new Toolbelt.LPMtlsClient();
     const headers = { authorization: 'Original Token' };
     const body = {test:123};
     // mtls options are optional, note: set json to true, to automatically stringify body + set correct content header. And parse response to json.
     const mtlsOptions = { timeout:10000, json: true }
     const response = await target.get(`https://some-lpmtls-endpoint.com`, headers);
     const { statusCode, headers, body } = await target.post(`https://some-lpmtls-endpoint.com`, headers, body, mtlsOptions);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

ILpMtlsClient


MTLSClient()

static MTLSClient(clientTLS): IMtlsClient

Returns an MTLS Client which is configured with the provided config. Please make sure that you set allowSelfSigned to true when calling an endpoint that relies on a self-signed cert. Another alternative would be to leverage the ca cert, that needs to be passed via the clientTLS config. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#imtlsclient)

Parameters
clientTLS

ClientTLS

Client Bundle consisting of cert + key and optionally the ca cert

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';
 try{
     let clientBundle: string[] = ['someclientcert', 'someclientkey', 'somecakey'];
     const [cert, key, ca] = clientBundle;
     const target = Toolbelt.MTLSClient({ cert, key, ca });
     const headers = { authorization: 'Original Token' };
     const body = {test:123};
     // mtls options are optional, note: set json to true, to automatically stringify body + set correct content header. And parse response to json.
     const mtlsOptions = { timeout:10000, json: true };
     const response = await target.get(`https://some-lpmtls-endpoint.com`, headers);
     const { statusCode, headers, body } = await target.post(`https://some-lpmtls-endpoint.com`, headers, body, mtlsOptions);
     // const { statusCode, headers, body } = await target.put(`https://some-lpmtls-endpoint.com`, headers, body);
     // const { statusCode, headers, body } = await target.delete(`https://some-lpmtls-endpoint.com`, headers, body);
     // const { statusCode, headers, body } = await target.options(`https://some-lpmtls-endpoint.com`, headers, body);
     // const { statusCode, headers, body } = await target.patch(`https://some-lpmtls-endpoint.com`, headers, body);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

IMtlsClient


OrchestratorClient()

static OrchestratorClient(): IOrchestratorClient

Returns an OrchestratorClient which can be used to invoke other functions Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#iorchestratorclient)

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';
 const orchestratorClient = Toolbelt.OrchestratorClient();
 try{
     const invocations = [
          { uuid: 'f196e196-7cf2-4d32-bbd6-4173eb736b08', payload: {}, headers: { header1: 'value1', header2: 'value2' }},
          { uuid: 'e2431d9c-6dfc-6cc6-ddd5-1111eb731b07', payload: {}, headers: {} },
          { uuid: 'c451e193-ccfc-cd31-b556-2343ec145601', payload: {} },
      ];

     const response = await orchestratorClient.invoke(invocations);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

IOrchestratorClient


SDEUtil()

static SDEUtil(): ISDEUtil

Returns a SDE Util, which can be used to add SDEs and other SDE related operations. This api is NOT realtime, i.e. requests can take more than 30s. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#isdeutil) For attributes and types you can find more details about them here (documentation)[https://developers.liveperson.com/engagement-attributes-types-of-engagement-attributes.html]

Basic Example

 import { Toolbelt } from 'core-functions-toolbelt';
 const sDEUtil = Toolbelt.SDEUtil();
 try{
     const visitorId = '123';
     const sessionId = '222';
     const engagementAttributes = [{ type: 'sampleType' }];
     await sdeUtil.addSDEs(engagementAttributes, visitorId, sessionId);
     const conversationParam = 'sampleparam'
     sdeUtil.getSDEsFromConv(conversationParam);
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Returns

ISDEUtil


SecretClient()

static SecretClient(options?): ISecretClient

Returns a Secret Client, which is configured to allow read and update access to the secret storage of the Site ID. IMPORTANT: Secrets are by default cached. If you want to leverage the lastest values you need to explicitly opt in by setting { useCache: false, } Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-interfaces.html#isecretclient)

Basic example

 import { Toolbelt } from 'core-functions-toolbelt';
 const secretClient = Toolbelt.SecretClient();
 try{
     // Get refreshToken from secret storage
     const { value } = await secretClient.readSecret('refreshToken');

     // write/update token to secret storage
     await secretClient.writeSecret({
           key: 'refreshToken',
           value: 'sampleValue'
       });
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }

Disable secret cache (in case fresh secrets are required)

 import { Toolbelt } from 'core-functions-toolbelt';
 const secretClient = Toolbelt.SecretClient();
 try{
     // Get fresh secret from secret storage
    const { value } = await secretClient.readSecret("SecretName", { useCache: false, });
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }
Parameters
options?

Partial<SecretClientOptions>

Returns

ISecretClient


SFClient()

static SFClient(): object

Returns
connectToSalesforce()

connectToSalesforce: (params) => Connection = ConnectToSalesforce

ConnectToSalesforce creates a standard JSForce Connection object and preconfigures it to allow it to communicate and send Requests in the correct format.

####### Parameters

####### params

ConnectionConfig

####### Returns

Connection

Salesforce {Connection}

Example

    ConnectToSalesforce({loginUrl:'https://test.salesforce.com',accessToken:'secret',refreshToken:'secret'})
Deprecated

This Salesforce client wrapper is deprecated and will be removed in a future major version. For better maintainability, please use the '@jsforce/jsforce-node' library directly.

Example

// Before import { Toolbelt } from 'core-functions-toolbelt'; const sFClient = Toolbelt.SFClient();

// After import { Connection } from '@jsforce/jsforce-node'; const conn = new Connection(params);

Returns a Nodejs Salesforce client. Read the full (documentation)(liveperson-functions-v2-toolbelt-documentation-classes.html#sfclient) Use the official (SalesForce documentation)[https://jsforce.github.io/document/] for all features.

Basic example

 import { Toolbelt } from 'core-functions-toolbelt';
 const sFClient = Toolbelt.SFClient();
 try{
     const conn = sFClient.connectToSalesforce({ loginUrl: 'https://login.salesforce.com', accessToken:'secret',refreshToken:'secret' });
     const result = await conn.sobject('Account').describe();
  } catch (error){
     console.error(`Received following error message: ${error.message}`);
  }