Using Salesforce Subscriber in NodeJs Typescript using jsforce
Published: 2023-03-01 05:18:30

Setting up a subscriber in Node.js Typescript to Salesforce Opportunities using change control events.

Make sure you have a Salesforce Developer account and a connected app. You can create a connected app in your Salesforce account by going to Setup > App Manager > New Connected App.

Install the `@salesforce/core` and `jsforce` packages in your Node.js project by running the following commands:
```typescript
npm install @salesforce/core jsforce
```
Create a new Typescript file and import the necessary modules:

```typescript
import { Connection, OAuth2 } from 'jsforce';
import { createStreamClient, ReplayExtension, CLIENT_CONFIG_DEFAULT } from '@salesforce/core';
```
Create a function to authenticate with Salesforce using OAuth2 authentication:
```typescript
async function authenticateWithSalesforce(): Promise<Connection> {
  const oauth2 = new OAuth2({
    clientId: 'your-connected-app-client-id',
    clientSecret: 'your-connected-app-client-secret',
    redirectUri: 'http://localhost:3000/oauth2/callback'
  });
  const authUrl = oauth2.getAuthorizationUrl();
  console.log('Open the following URL and grant access to your Salesforce account:');
  console.log(authUrl);
  
  // After the user grants access and is redirected to the callback URL,
  // extract the authorization code and exchange it for an access token
  const conn = new Connection({
    oauth2,
  });
  const authCode = 'the-authorization-code-you-received';
  const authResult = await conn.authorize(authCode);
  
  console.log('Successfully authenticated with Salesforce');
  return conn;
}
```

Note: Replace `your-connected-app-client-id` and `your-connected-app-client-secret` with the values for your connected app, and make sure to configure the callback URL in your connected app settings.Create a function to set up a Change Data Capture (CDC) stream for the Opportunities object:
```typescript
async function subscribeToOpportunityChanges(conn: Connection) {
  // Create a CDC stream client
  const streamClient = await createStreamClient(conn, CLIENT_CONFIG_DEFAULT);
  
  // Create a replay extension to receive missed events
  const replayExtension = new ReplayExtension();
  
  // Subscribe to change events for the Opportunities object
  const subscription = await streamClient.subscribe({
    topic: 'OpportunityChangeEvent',
    // Use the replay extension to receive missed events
    // (optional, but recommended)
    replay: replayExtension,
    // Set the initial position to start streaming from
    // (optional, defaults to the latest available position)
    ...replayExtension.getInitialPosition(),
    // Callback function to handle incoming events
    // (replace with your own implementation)
    onEvent: async (event) => {
      console.log(`Received OpportunityChangeEvent: ${JSON.stringify(event)}`);
      // Do something with the event data, e.g. update a local database
    },
  });
  
  console.log('Successfully subscribed to OpportunityChangeEvent');
}
```
Call the `authenticateWithSalesforce` and `subscribeToOpportunityChanges` functions to start streaming CDC events for the Opportunities object:
```typescript
(async () => {
  const conn = await authenticateWithSalesforce();
  await subscribeToOpportunityChanges(conn);
})();
```

That's it! You should now be able to receive real-time change events for the Opportunities object in your Node.js application. Note that this is just a basic example - you can customize the `onEvent` callback function to handle the event data in any way you like.

If you encounter an error with the code, you can add error handling to the `subscribeToOpportunityChanges` function to catch any errors that may occur during the subscription process:
```typescript
async function subscribeToOpportunityChanges(conn: Connection) {
  try {
    // Create a CDC stream client
    const streamClient = await createStreamClient(conn, CLIENT_CONFIG_DEFAULT);
    
    // Create a replay extension to receive missed events
    const replayExtension = new ReplayExtension();
    
    // Subscribe to change events for the Opportunities object
    const subscription = await streamClient.subscribe({
      topic: 'OpportunityChangeEvent',
      // Use the replay extension to receive missed events
      // (optional, but recommended)
      replay: replayExtension,
      // Set the initial position to start streaming from
      // (optional, defaults to the latest available position)
      ...replayExtension.getInitialPosition(),
      // Callback function to handle incoming events
      // (replace with your own implementation)
      onEvent: async (event) => {
        console.log(`Received OpportunityChangeEvent: ${JSON.stringify(event)}`);
        // Do something with the event data, e.g. update a local database
      },
    });
    
    console.log('Successfully subscribed to OpportunityChangeEvent');
  } catch (error) {
    console.error(`Failed to subscribe to OpportunityChangeEvent: ${error}`);
  }
}
```
If you want to customize the CDC subscription, you can refer to the Salesforce Change Data Capture Developer Guide for more information on available options and best practices.

That's it! You should now be able to receive real-time change events for the Opportunities object in your Node.js application using the Change Data Capture feature in Salesforce.