### Install Dependencies Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Install the salesforce-pubsub-api-client and dotenv packages using npm. ```bash npm install salesforce-pubsub-api-client dotenv ``` -------------------------------- ### JavaScript Pub/Sub API Client Example Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents This example demonstrates how to connect to the Salesforce Pub/Sub API, subscribe to AccountChangeEvent, and handle incoming events. It's configured to listen for a maximum of 3 events before closing the connection. ```javascript import * as dotenv from 'dotenv'; import PubSubApiClient from 'salesforce-pubsub-api-client'; async function run() { try { // Load config from .env file dotenv.config(); // Build and connect Pub/Sub API client const client = new PubSubApiClient({ authType: 'username-password', loginUrl: process.env.SALESFORCE_LOGIN_URL, username: process.env.SALESFORCE_USERNAME, password: process.env.SALESFORCE_PASSWORD, userToken: process.env.SALESFORCE_TOKEN }); await client.connect(); // Prepare event callback const subscribeCallback = (subscription, callbackType, data) => { switch (callbackType) { case 'event': // Event received console.log( `${subscription.topicName} - Handling ${data.payload.ChangeEventHeader.entityName} change event ` + `with ID ${data.replayId} ` + `(${subscription.receivedEventCount}/${subscription.requestedEventCount} ` + `events received so far)` ); // Safely log event payload as a JSON string console.log( JSON.stringify( data, (key, value) => /* Convert BigInt values into strings and keep other types unchanged */ typeof value === 'bigint' ? value.toString() : value, 2 ) ); break; case 'lastEvent': // Last event received console.log( `${subscription.topicName} - Reached last of ${subscription.requestedEventCount} requested event on channel. Closing connection.` ); break; case 'end': // Client closed the connection console.log('Client shut down gracefully.'); break; } }; // Subscribe to 3 account change event client.subscribe('/data/AccountChangeEvent', subscribeCallback, 3); } catch (error) { console.error(error); } } run(); ``` -------------------------------- ### Example Connection Output Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents This output indicates a successful connection to Salesforce and the Pub/Sub API, along with the subscription request being sent. ```text Connected to Salesforce org https://pozil-dev-ed.my.salesforce.com (00D58000000arpqEAA) as grpc@pozil.com Connected to Pub/Sub API endpoint api.pubsub.salesforce.com:7443 /data/AccountChangeEvent - Subscribe request sent for 3 events ``` -------------------------------- ### Example Event Handling Output Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents This output shows an Account change event being received and processed, including details about the event and its payload. ```text /data/AccountChangeEvent - Received 1 events, latest replay ID: 18098167 /data/AccountChangeEvent - Handling Account change event with ID 18098167 (1/3 events received so far) { "id": "9b77cea1-a923-4766-ad50-a1797d9b39fd", "schemaId": "a01VpgrsZNJdn-7KStJcxQ", "replayId": 18098167, "payload": { "ChangeEventHeader": { "entityName": "Account", "recordIds": [ "0014H00002LbR7QQAV" ], "changeType": "UPDATE", "changeOrigin": "com/salesforce/api/soap/58.0;client=SfdcInternalAPI/", "transactionKey": "000046c7-a642-11e2-c29b-229c6786473e", "sequenceNumber": 1, "commitTimestamp": 1696444513000, "commitNumber": 11657372702432, "commitUser": "00558000000yFyDAAU", "nulledFields": [], "diffFields": [], "changedFields": [ "LastModifiedDate", "BillingAddress.City", "BillingAddress.State" ] }, "Name": null, "Type": null, "ParentId": null, "BillingAddress": { "Street": null, "City": "San Francisco", "State": "CA", "PostalCode": null, "Country": null, "StateCode": null, "CountryCode": null, "Latitude": null, ``` -------------------------------- ### Salesforce Change Event Payload Example Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=code This example shows a typical change event payload from the Salesforce Pub/Sub API. Note that fields not modified in the event will have a null value. Use `ChangeEventHeader` fields like `nulledFields`, `diffFields`, and `changedFields` to determine actual changes. ```json { "schema": "...", "payload": { "Id": "001R0000003456789", "Name": "Sample Account", "BillingStreet": "123 Main St", "BillingCity": "Anytown", "BillingState": "CA", "BillingPostalCode": "90210", "BillingCountry": "USA", "BillingLatitude": null, "BillingLongitude": null, "ShippingStreet": null, "ShippingCity": null, "ShippingState": null, "ShippingPostalCode": null, "ShippingCountry": null, "ShippingLatitude": null, "ShippingLongitude": null, "GeocodeAccuracy": null }, "ChangeEventHeader": { "entityName": "Account", "changeType": "UPDATE", "changedFields": [ "BillingState", "BillingCity", "LastModifiedDate" ], "changeOrigin": "api", "transactionKey": "...", "sequenceNumber": 1, "overChangeHints": null, "nulledFields": [], "diffFields": [] } } ``` -------------------------------- ### v5 Event Handling with Callback Function Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents In v5, a synchronous callback function is used for event handling, ensuring events are received in the correct order. This example demonstrates subscribing to events using a callback. ```javascript const subscribeCallback = (subscription, callbackType, data) => { // Event handling logic goes here }; // Subscribe to account change events await client.subscribe('/data/AccountChangeEvent', subscribeCallback); ``` -------------------------------- ### Subscribe with a replay ID Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Subscribes to events starting from a specific replay ID. ```APIDOC ## Subscribe with a replay ID Subscribes to events starting from a specific replay ID. ### Method `client.subscribeFromReplayId(topic, callback, replayFrom, maxMessages)` ### Parameters - **topic** (string) - Required - The topic to subscribe to. - **callback** (function) - Required - The callback function to handle incoming events. - **replayFrom** (number) - Required - The replay ID to start subscribing from. - **maxMessages** (number) - Optional - The maximum number of messages to receive. ``` -------------------------------- ### v4 Event Handling with EventEmitter Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents In v4 and earlier versions, an asynchronous EventEmitter was used to receive incoming messages and lifecycle events. This example shows how to subscribe to events and handle incoming data. ```javascript const eventEmitter = await client.subscribe( '/data/AccountChangeEvent' ); // Handle incoming events eventEmitter.on('data', (event) => { // Event handling logic goes here }): ``` -------------------------------- ### getConnectivityState() Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Gets the gRPC connectivity state from the current channel. Returns a Promise holding the channel's connectivity state. ```APIDOC ## async getConnectivityState() → {Promise} ### Description Gets the gRPC connectivity state from the current channel. ### Returns - Promise that holds the channel's connectivity state. ``` -------------------------------- ### Subscribe to events from a specific replay ID Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Subscribe to events starting from a given replay ID. This is useful for resuming event streams. ```APIDOC ## Subscribe with a replay ID ### Description Subscribe to events starting from a given replay ID. This is useful for resuming event streams. ### Method `client.subscribeFromReplayId(topic, subscribeCallback, replayFrom, maxMessages)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to subscribe to (e.g., `/data/AccountChangeEvent`). #### Query Parameters - **subscribeCallback** (function) - Required - The callback function to handle incoming events. - **replayFrom** (number) - Required - The replay ID to start subscribing from. - **maxMessages** (number) - Optional - The maximum number of messages to retrieve. ``` -------------------------------- ### Subscribe to Events from a Replay ID Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Subscribe to a specified number of events starting from a given replay ID. This is useful for resuming event streams. ```javascript await client.subscribeFromReplayId( '/data/AccountChangeEvent', subscribeCallback, 5, 17092989 ); ``` -------------------------------- ### Run the Sample Script Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Execute the sample JavaScript file using Node.js. ```bash node sample.js ``` -------------------------------- ### Configure Environment Variables Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Create a .env file at the root of your project and populate it with your Salesforce credentials and login URL. ```env SALESFORCE_LOGIN_URL=... SALESFORCE_USERNAME=... SALESFORCE_PASSWORD=... SALESFORCE_TOKEN=... ``` -------------------------------- ### subscribeFromReplayId Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Subscribes to a topic and retrieves past events starting from a specified replay ID. ```APIDOC ## subscribeFromReplayId(topicName, subscribeCallback, numRequested, replayId) ### Description Subscribes to a topic and retrieves past events starting from a replay ID. ### Parameters #### Path Parameters - **topicName** (string) - Required - name of the topic that we're subscribing to - **subscribeCallback** (SubscribeCallback) - Required - subscribe callback function - **numRequested** (number) - Optional - number of events requested. If `null`, the client keeps the subscription alive forever. - **replayId** (number) - Required - replay ID ``` -------------------------------- ### connect() Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Authenticates with Salesforce then connects to the Pub/Sub API. Resolves once the connection is established. ```APIDOC ## async connect() → {Promise.} ### Description Authenticates with Salesforce then connects to the Pub/Sub API. ### Returns - Promise that resolves once the connection is established. ``` -------------------------------- ### PubSubApiClient Constructor Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Builds a new Pub/Sub API client. Accepts configuration and an optional logger. ```APIDOC ## PubSubApiClient(configuration, [logger]) ### Description Builds a new Pub/Sub API client. ### Parameters #### Path Parameters - **configuration** (Configuration) - Required - The client configuration (authentication...). - **logger** (Logger) - Optional - An optional custom logger. The client uses the console if no value is supplied. ``` -------------------------------- ### PubSubApiClient Constructor Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=code Builds a new Pub/Sub API client instance. ```APIDOC ## PubSubApiClient Client for the Salesforce Pub/Sub API #### `PubSubApiClient(configuration, [logger])` Builds a new Pub/Sub API client. Name | Type | Description ---|---|--- `configuration` | Configuration | The client configuration (authentication...). `logger` | Logger | An optional custom logger. The client uses the console if no value is supplied. ``` -------------------------------- ### Configure Custom Logger with Pub/Sub API Client Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Pass a custom logger, such as pino, to the PubSubApiClient constructor for improved performance over the default console logger. Ensure the logger is initialized before creating the client. ```javascript import pino from 'pino'; const config = { /* your config goes here */ }; const logger = pino(); const client = new PubSubApiClient(config, logger); ``` -------------------------------- ### v4 vs v5 Event Handling Comparison Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=versions Illustrates the difference in event handling between v4 (EventEmitter) and v5 (synchronous callback) of the Pub/Sub API client. ```javascript const eventEmitter = await client.subscribe( '/data/AccountChangeEvent' ); // Handle incoming events eventEmitter.on('data', (event) => { // Event handling logic goes here }): ``` ```javascript const subscribeCallback = (subscription, callbackType, data) => { // Event handling logic goes here }; // Subscribe to account change events await client.subscribe('/data/AccountChangeEvent', subscribeCallback); ``` -------------------------------- ### User Supplied Authentication Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Use this authentication method if you already have an authenticated Salesforce client, such as one obtained with jsforce. Pass the existing access token, instance URL, and organization ID. ```javascript const client = new PubSubApiClient({ authType: 'user-supplied', accessToken: sfConnection.accessToken, instanceUrl: sfConnection.instanceUrl, organizationId: sfConnection.userInfo.organizationId }); ``` -------------------------------- ### Username/Password Flow Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Configure and instantiate the PubSubApiClient using a username and password. This method is not recommended for production environments. ```APIDOC ## Username/Password Flow ### Description Configure and instantiate the PubSubApiClient using a username and password. This method is not recommended for production environments. ### Code Example ```javascript const client = new PubSubApiClient({ authType: 'username-password', loginUrl: process.env.SALESFORCE_LOGIN_URL, username: process.env.SALESFORCE_USERNAME, password: process.env.SALESFORCE_PASSWORD, userToken: process.env.SALESFORCE_TOKEN }); ``` ``` -------------------------------- ### User Supplied Authentication Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Instantiate the PubSubApiClient using pre-existing authentication details, such as those obtained from jsforce. ```APIDOC ## User Supplied Authentication ### Description Instantiate the PubSubApiClient using pre-existing authentication details, such as those obtained from jsforce. ### Code Example ```javascript const client = new PubSubApiClient({ authType: 'user-supplied', accessToken: sfConnection.accessToken, instanceUrl: sfConnection.instanceUrl, organizationId: sfConnection.userInfo.organizationId }); ``` ``` -------------------------------- ### Publish a batch of platform events Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=readme Publishes a batch of platform events using the `publishBatch` method. A callback function is used to handle the publish response. ```APIDOC ## Publish a batch of platform events ### Description Publishes a batch of platform events using the `publishBatch` method. A callback function is used to handle the publish response. ### Method `client.publishBatch(topic, events, callback)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic of the events (e.g., `/event/Sample__e`). - **events** (array) - Required - An array of event objects, each with a `payload` property. - **callback** (function) - Required - A callback function to handle the publish response. ### Request Example ```javascript // Prepare publish callback const publishCallback = (info, callbackType, data) => { switch (callbackType) { case 'publishResponse': console.log(JSON.stringify(data)); break; } }; // Prepare events const events = [ { payload: { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type } } ]; // Publish event batch client.publishBatch('/event/Sample__e', events, publishCallback); ``` ``` -------------------------------- ### Publish a batch of platform events Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=code Publishes a batch of platform events using the `publishBatch` method. ```APIDOC ## Publish a batch of platform events ### Description Publishes a batch of platform events using the `publishBatch` method. ### Method `client.publishBatch(topic, events, publishCallback)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic of the events to publish (e.g., `/event/Sample__e`). #### Request Body - **events** (array) - Required - An array of event objects, where each object has a `payload` property. - **payload** (object) - Required - The event payload. Fields like `CreatedDate` and `CreatedById` are required, and custom fields like `Message__c` need to be specified with their type (e.g., `{ string: 'Hello world' }`). #### Callback - **publishCallback** (function) - Required - A callback function to handle the publish response. It receives `info`, `callbackType`, and `data`. - `callbackType`: 'publishResponse' indicates the response data. - `data`: The actual publish result. ### Request Example ```javascript // Prepare publish callback const publishCallback = (info, callbackType, data) => { switch (callbackType) { case 'publishResponse': console.log(JSON.stringify(data)); break; } }; // Prepare events const events = [ { payload: { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type } } ]; // Publish event batch client.publishBatch('/event/Sample__e', events, publishCallback); ``` ``` -------------------------------- ### Publish a Batch of Platform Events Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Use `publishBatch` to efficiently publish multiple platform events. A callback function is used to receive publish responses. ```javascript // Prepare publish callback const publishCallback = (info, callbackType, data) => { switch (callbackType) { case 'publishResponse': console.log(JSON.stringify(data)); break; } }; // Prepare events const events = [ { payload: { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type } } ]; // Publish event batch client.publishBatch('/event/Sample__e', events, publishCallback); ``` -------------------------------- ### OAuth 2.0 Client Credentials Flow Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Instantiate the PubSubApiClient using the OAuth 2.0 client credentials flow, suitable for server-to-server integrations. ```APIDOC ## OAuth 2.0 Client Credentials Flow (client_credentials) ### Description Instantiate the PubSubApiClient using the OAuth 2.0 client credentials flow, suitable for server-to-server integrations. ### Code Example ```javascript const client = new PubSubApiClient({ authType: 'oauth-client-credentials', loginUrl: process.env.SALESFORCE_LOGIN_URL, clientId: process.env.SALESFORCE_CLIENT_ID, clientSecret: process.env.SALESFORCE_CLIENT_SECRET }); ``` ``` -------------------------------- ### Publish a batch of platform events Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Publishes a batch of platform events. This method is recommended for publishing multiple events for better performance. ```APIDOC ## Publish a batch of platform events Publishes a batch of platform events. This method is recommended for publishing multiple events for better performance. ### Method `client.publishBatch(topic, events, callback)` ### Parameters - **topic** (string) - Required - The topic of the events to publish. - **events** (array) - Required - An array of event objects, each with a `payload` property. - **callback** (function) - Required - A callback function to handle publish responses. ### Request Example ```javascript // Prepare publish callback const publishCallback = (info, callbackType, data) => { switch (callbackType) { case 'publishResponse': console.log(JSON.stringify(data)); break; } }; // Prepare events const events = [ { payload: { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type } } ]; // Publish event batch client.publishBatch('/event/Sample__e', events, publishCallback); ``` ``` -------------------------------- ### Publish a Single Platform Event Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Use this method to publish a single platform event. For best performance with multiple events, consider using `publishBatch`. ```javascript const payload = { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type }; const publishResult = await client.publish('/event/Sample__e', payload); console.log('Published event: ', JSON.stringify(publishResult)); ``` -------------------------------- ### Username/Password Flow Authentication Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents This flow is suitable for testing but not recommended for production due to security considerations. Provide login URL, username, password, and a user token. ```javascript const client = new PubSubApiClient({ authType: 'username-password', loginUrl: process.env.SALESFORCE_LOGIN_URL, username: process.env.SALESFORCE_USERNAME, password: process.env.SALESFORCE_PASSWORD, userToken: process.env.SALESFORCE_TOKEN }); ``` -------------------------------- ### Subscribe to Earliest Events in Retention Window Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Subscribe to a specified number of the earliest available events within the Pub/Sub retention window. Useful for catching up on missed events. ```javascript await client.subscribeFromEarliestEvent( '/data/AccountChangeEvent', subscribeCallback, 3 ); ``` -------------------------------- ### Subscribe Using a Managed Subscription Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Subscribe to events using a managed subscription, which offloads replay ID tracking to the server. This involves creating a subscription via the tooling API first. ```javascript await client.subscribeWithManagedSubscription( 'Managed_Sample_PE', subscribeCallback, 3 ); ``` -------------------------------- ### Subscribe to the earliest events in the retention window Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Subscribe to a specified number of the earliest available events within the event retention window. ```APIDOC ## Subscribe to past events in retention window ### Description Subscribe to a specified number of the earliest available events within the event retention window. ### Method `client.subscribeFromEarliestEvent(topic, subscribeCallback, maxMessages)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to subscribe to (e.g., `/data/AccountChangeEvent`). #### Query Parameters - **subscribeCallback** (function) - Required - The callback function to handle incoming events. - **maxMessages** (number) - Required - The maximum number of earliest events to retrieve. ``` -------------------------------- ### Subscribe using a managed subscription Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Subscribe to events using a managed subscription, allowing the server to track replay IDs. This makes the client application stateless. ```APIDOC ## Subscribe using a managed subscription ### Description Subscribe to events using a managed subscription, allowing the server to track replay IDs. This makes the client application stateless. ### Method `client.subscribeWithManagedSubscription(subscriptionName, subscribeCallback, maxMessages)` ### Parameters #### Path Parameters - **subscriptionName** (string) - Required - The name of the managed event subscription. #### Query Parameters - **subscribeCallback** (function) - Required - The callback function to handle incoming events and subscription updates. - **maxMessages** (number) - Optional - The maximum number of messages to retrieve initially. ``` ```APIDOC ## Commit Replay ID for Managed Subscription ### Description Commit the last received replay ID for a managed subscription to the server. ### Method `client.commitReplayId(subscriptionId, lastReplayId)` ### Parameters #### Path Parameters - **subscriptionId** (string) - Required - The ID of the managed subscription. - **lastReplayId** (number) - Required - The last replay ID received. ``` ```APIDOC ## Request Additional Managed Events ### Description Request additional events to be sent for a managed subscription. ### Method `client.requestAdditionalManagedEvents(subscriptionId, numAdditionalEvents)` ### Parameters #### Path Parameters - **subscriptionId** (string) - Required - The ID of the managed subscription. - **numAdditionalEvents** (number) - Required - The number of additional events to request. ``` -------------------------------- ### Subscribe using a managed subscription Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=readme Subscribes to events using a managed subscription, where the server tracks replay IDs. This involves creating a subscription, subscribing, committing replay IDs, and optionally requesting additional events. ```APIDOC ## Subscribe using a managed subscription ### Description Subscribes to events using a managed subscription, where the server tracks replay IDs. This involves creating a subscription, subscribing, committing replay IDs, and optionally requesting additional events. ### Methods 1. `client.subscribeWithManagedSubscription(subscriptionName, callback, eventCount)` 2. `client.commitReplayId(subscriptionId, lastReplayId)` 3. `client.requestAdditionalManagedEvents(subscriptionId, numberOfEvents)` ### Parameters #### `subscribeWithManagedSubscription` Parameters - **subscriptionName** (string) - Required - The name of the managed event subscription. - **callback** (function) - Required - The callback function to handle received events and subscription information. - **eventCount** (number) - Required - The number of events to initially retrieve. #### `commitReplayId` Parameters - **subscriptionId** (string) - Required - The ID of the managed subscription. - **lastReplayId** (number) - Required - The last replay ID received. #### `requestAdditionalManagedEvents` Parameters - **subscriptionId** (string) - Required - The ID of the managed subscription. - **numberOfEvents** (number) - Required - The number of additional events to request. ### Request Example ```javascript // Subscribe to 3 events from a managed event subscription await client.subscribeWithManagedSubscription( 'Managed_Sample_PE', subscribeCallback, 3 ); // Using the subscription information sent in the subscribe callback, frequently commit the last replay ID client.commitReplayId( subscription.subscriptionId, subscription.lastReplayId ); // Optionally, request additional events client.requestAdditionalManagedEvents(subscription.subscriptionId, 3); ``` ``` -------------------------------- ### Subscribe Using a Managed Subscription Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Subscribe to events using a managed subscription, which delegates replay ID tracking to the server. This allows for stateless client applications. ```javascript await client.subscribeWithManagedSubscription( 'Managed_Sample_PE', subscribeCallback, 3 ); ``` ```javascript client.commitReplayId( subscription.subscriptionId, subscription.lastReplayId ); ``` ```javascript client.requestAdditionalManagedEvents(subscription.subscriptionId, 3); ``` -------------------------------- ### publishBatch(topicName, events, publishCallback) Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=code Publishes a batch of events to a specified topic using the gRPC client's publish stream. Requires a callback for handling publish responses. ```APIDOC #### `async publishBatch(topicName, events, publishCallback)` Publishes a batch of events using the gRPC client's publish stream. Name | Type | Description ---|---|--- `topicName` | string | name of the topic that we're publishing on `events` | PublisherEvent[] | events to be published `publishCallback` | PublishCallback | callback function for handling publish responses. ``` -------------------------------- ### publish(topicName, payload, [correlationKey]) Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=readme Publishes a payload to a topic using the gRPC client. Returns a Promise holding a PublishResult object with replayId and correlationKey. ```APIDOC ## async publish(topicName, payload, [correlationKey]) → {Promise.} ### Description Publishes an payload to a topic using the gRPC client. This is a synchronous operation, use `publishBatch` when publishing event batches. Returns: Promise holding a `PublishResult` object with `replayId` and `correlationKey`. ### Parameters #### Path Parameters - **topicName** (string) - name of the topic that we're publishing on - **payload** (Object) - payload of the event that is being published - **correlationKey** (string) - optional correlation key. If you don't provide one, we'll generate a random UUID for you. ``` -------------------------------- ### publishBatch(topicName, events, publishCallback) Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=readme Publishes a batch of events using the gRPC client's publish stream. ```APIDOC ## async publishBatch(topicName, events, publishCallback) ### Description Publishes a batch of events using the gRPC client's publish stream. ### Parameters #### Path Parameters - **topicName** (string) - name of the topic that we're publishing on - **events** (PublisherEvent[]) - events to be published - **publishCallback** (PublishCallback) - callback function for handling publish responses. ``` -------------------------------- ### publish(topicName, payload, [correlationKey]) Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Publishes a payload to a topic using the gRPC client. Returns a Promise holding a PublishResult object. ```APIDOC ## async publish(topicName, payload, [correlationKey]) → {Promise.} ### Description Publishes an payload to a topic using the gRPC client. This is a synchronous operation, use `publishBatch` when publishing event batches. ### Parameters #### Path Parameters - **topicName** (string) - Required - name of the topic that we're publishing on - **payload** (Object) - Required - payload of the event that is being published - **correlationKey** (string) - Optional - optional correlation key. If you don't provide one, we'll generate a random UUID for you. ### Returns - Promise holding a `PublishResult` object with `replayId` and `correlationKey`. ``` -------------------------------- ### Subscribe to past events in retention window Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Subscribes to the earliest available events within the retention window. ```APIDOC ## Subscribe to past events in retention window Subscribes to the earliest available events within the retention window. ### Method `client.subscribeFromEarliestEvent(topic, callback, maxMessages)` ### Parameters - **topic** (string) - Required - The topic to subscribe to. - **callback** (function) - Required - The callback function to handle incoming events. - **maxMessages** (number) - Required - The maximum number of messages to retrieve. ``` -------------------------------- ### Subscribe to past events in retention window Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=versions Subscribes to the earliest available past events within the retention window. ```APIDOC ## Subscribe to past events in retention window Subscribes to the earliest available past events within the retention window. ### Method `client.subscribeFromEarliestEvent(topic, subscribeCallback, maxMessages)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to subscribe to (e.g., `/data/AccountChangeEvent`). - **subscribeCallback** (function) - Required - The callback function to handle incoming events. - **maxMessages** (number) - Required - The maximum number of earliest events to retrieve. ``` -------------------------------- ### Subscribe to past events in retention window Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=readme Subscribes to the earliest available past events within the retention window. ```APIDOC ## Subscribe to past events in retention window ### Description Subscribes to the earliest available past events within the retention window. ### Method `client.subscribeFromEarliestEvent(topic, callback, eventCount)` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to subscribe to (e.g., `/data/AccountChangeEvent`). - **callback** (function) - Required - The callback function to handle received events. - **eventCount** (number) - Required - The number of earliest events to retrieve. ``` -------------------------------- ### OAuth 2.0 Client Credentials Flow Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents This authentication flow is used for server-to-server integrations. Configure with login URL, client ID, and client secret. ```javascript const client = new PubSubApiClient({ authType: 'oauth-client-credentials', loginUrl: process.env.SALESFORCE_LOGIN_URL, clientId: process.env.SALESFORCE_CLIENT_ID, clientSecret: process.env.SALESFORCE_CLIENT_SECRET }); ``` -------------------------------- ### OAuth 2.0 JWT Bearer Flow Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependencies Instantiate the PubSubApiClient using the OAuth 2.0 JWT bearer flow, which is the most secure option and recommended for production use. ```APIDOC ## OAuth 2.0 JWT Bearer Flow ### Description Instantiate the PubSubApiClient using the OAuth 2.0 JWT bearer flow, which is the most secure option and recommended for production use. ### Code Example ```javascript // Read private key file const privateKey = fs.readFileSync(process.env.SALESFORCE_PRIVATE_KEY_FILE); // Build PubSub client const client = new PubSubApiClient({ authType: 'oauth-jwt-bearer', loginUrl: process.env.SALESFORCE_JWT_LOGIN_URL, clientId: process.env.SALESFORCE_JWT_CLIENT_ID, username: process.env.SALESFORCE_USERNAME, privateKey }); ``` ``` -------------------------------- ### subscribeWithManagedSubscription Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=dependents Subscribes to a topic using a managed subscription. Throws an error if the managed subscription does not exist or is not in the 'RUN' state. ```APIDOC ## subscribeWithManagedSubscription(subscriptionIdOrName, subscribeCallback, [numRequested]) ### Description Subscribes to a topic thanks to a managed subscription. Throws an error if the managed subscription does not exist or is not in the `RUN` state. ### Parameters #### Path Parameters - **subscriptionIdOrName** (string) - Required - managed subscription ID or developer name - **subscribeCallback** (SubscribeCallback) - Required - subscribe callback function - **numRequested** (number) - Optional - optional number of events requested. If not supplied or null, the client keeps the subscription alive forever. ``` -------------------------------- ### Publish a single platform event Source: https://www.npmjs.com/package/salesforce-pubsub-api-client Publishes a single platform event with the specified payload. For best performance with event batches, use `publishBatch`. ```APIDOC ## Publish a single platform event Publishes a single platform event with the specified payload. For best performance with event batches, use `publishBatch`. ### Method `client.publish(topic, payload)` ### Parameters - **topic** (string) - Required - The topic of the event to publish. - **payload** (object) - Required - The event payload. ### Request Example ```javascript const payload = { CreatedDate: new Date().getTime(), // Non-null value required but there's no validity check performed on this field CreatedById: '005_________', // Valid user ID Message__c: { string: 'Hello world' } // Field is nullable so we need to specify the 'string' type }; const publishResult = await client.publish('/event/Sample__e', payload); console.log('Published event: ', JSON.stringify(publishResult)); ``` ``` -------------------------------- ### Work with flow control for high volumes of events Source: https://www.npmjs.com/package/salesforce-pubsub-api-client?activeTab=code Implement event flow control to manage high volumes of incoming events and prevent the client from being overwhelmed. ```APIDOC ## Work with flow control for high volumes of events ### Description Implement event flow control to manage high volumes of incoming events and prevent the client from being overwhelmed. This is achieved by requesting a limited batch of events and then requesting additional batches as needed. ### Process 1. Pass a number of requested events in your subscribe call. 2. Handle the `lastEvent` callback type to detect the end of an event batch. 3. Subscribe to an additional batch of events with `client.requestAdditionalEvents(...)`. ### Methods #### `client.subscribe(topic, subscribeCallback, numRequestedEvents)` - **topic** (string) - Required - The topic to subscribe to (e.g., `/data/AccountChangeEvent`). - **subscribeCallback** (function) - Required - The callback function to handle events. It will receive `subscription`, `callbackType`, and `data`. - `callbackType`: 'event' for regular events, 'lastEvent' for the last event in a batch, 'end' for connection closure. - **numRequestedEvents** (number) - Required - The initial number of events to request in the first batch. #### `client.requestAdditionalEvents(eventEmitter, numEvents)` - **eventEmitter** (object) - Required - The event emitter object associated with the subscription. - **numEvents** (number) - Required - The number of additional events to request. ### Request Example ```javascript try { // Connect with the Pub/Sub API const client = new PubSubApiClient(/* config goes here */); await client.connect(); // Prepare event callback const subscribeCallback = (eventEmitter, callbackType, data) => { switch (callbackType) { case 'event': // Logic for handling a single event. break; case 'lastEvent': // Last event received console.log( `${eventEmitter.getTopicName()} - Reached last requested event on channel.` ); // Request 10 additional events client.requestAdditionalEvents(eventEmitter, 10); break; case 'end': // Client closed the connection console.log('Client shut down gracefully.'); break; } }; // Subscribe to a batch of 10 account change event await client.subscribe('/data/AccountChangeEvent', subscribeCallback, 10); } catch (error) { console.error(error); } ``` ```