Posted by Arjun on Friday 31st July 2020

Connect to Salesforce with Node.js

Salesforce

In this post, we gonna make a connection to Salesforce with Node.js and we will update the Salesforce Objects.

We will use node-salesforce npm module to authenticate with Salesforce. So let's install it.

Let initialize the project with npm init --yes and isntall node-salesforce as shown below.

$ mkdir salesforceDemo
$ cd salesforceDemo
$ npm init --yes
$ npm install node-salesforce

Once you install the dependency, let create a file called index.js, file name can be anything.

const salesForceLoginUrl = 'https://test.salesforce.com'
const salesForceLoginUser = "login user"
const salesForceAccountPassword = "account password"
const salesForceSecurityToken = "security token"
const sf = require('node-salesforce')

const connect = async () => {
    return new Promise((resolve, reject) => {
        const conn = new sf.Connection({
            loginUrl: salesForceLoginUrl
        })
        conn.login(salesForceLoginUser, `${salesForceAccountPassword}${salesForceSecurityToken}`, function (err, result) {
            if (err) { return reject(err) }
            return resolve(result)
        })
    });
}

(async() => {
   const salesForceConnct = await connect();
   console.log(salesForceConnct)
})()

update the connection settings with your salesforce details. After updating the details you can test your connection with node index.js and upon the success, you should get a response object with organizationId, id, URL.

Connect to Salesforce with Node.js

Fetech data from salesforce

const getObject = async(conn, objectName, where) => {
  return new Promise((resolve, reject) => {
    conn.sobject(objectName)
      .find(where)
      .execute(function(err, records) {
        if (err) { return reject(err) }
        return resolve(records)
      });
  });
}
//usage
(async() => {
  try {
   const salesForceConnct = await connect();
   const results = await getObject(salesForceConnct,'ObjectName',{'Id' : '1123455'});
   console.log(results);
  } catch(error) {
    console.log(error.toString());
  }
})()

Update salesforce data

const updateObject = async (conn, objectName, data) => {
  return new Promise((resolve, reject) => {
    conn.sobject(objectName).update(data, function (err, rets) {
      if (err) { return reject(err); }
      return resolve(rets);
    })
  });
}
//usage
(async() => {
  try {
   const salesForceConnct = await connect();
   const results = await updateObject (salesForceConnct,'ObjectName',{'Id' : '1123455', 'Name' :'Arjun'}); // it will update name where ID = 1123455
   console.log(results);
  } catch(error) {
    console.log(error.toString());
  }
})()

To update multiple rows, just send data in the array of objects formate.