Build force.com Apps with nforce and Node.js

In this tutorial you will learn how to use Node.js app along with nforce. nforce is a node.js module which allows integrations with force.com rest APIs.

../_images/node-nforce.png

Reference Source Code : force-node-nforce

Getting Started

  1. Create a Blanck nodejs express app

    $ express force-node-nforce
    
  2. Install dependencies

    npm install
    
  3. Setup connection.js to connect with force.com APIs

    $ mkdir lib
    $ cd lib
    $ vi connection.js
    

    Copy the following code to this file

    'use strict'
    
    var nforce = require('nforce');
    
    var org = nforce.createConnection({
      clientId: process.env.CLIENTID,
      clientSecret: process.env.CLIENTSECRET,
      redirectUri: 'http://localhost:3000/oauth/_callback',
      apiVersion: 'v34.0',
      environment: 'production',
      mode: 'single',
      autoRefresh: true
    });
    
    org.authenticate({ username: process.env.USERNAME,
                      password: process.env.PASSWORD},
      function(err, resp){
        if(!err) console.log('Successfully connected to Salesforce.
                              Cached token: ' + org.oauth.access_token);
        if(err) console.log('Cannot connect to Salesforce: ' + err);
    });
    
    module.exports = org;
    

    Setup the Environment Variables

    $ export USERNAME=...
    $ export PASSWORD=..
    $ export CLIENTID=..
    $ export CLIENTSECRET=...
    

Accounts

Rest Endpoints exposed for Accounts

  • List Accounts : GET /accounts
  • Create Account : POST /create-account
  • Delete Account : DELETE /delete-account

List Accounts

  1. Modify route/index.js to add the the endpoint :code:’/accounts’. We call the query function on org and pass the SOQL query. Results and retured and rendered through index-accounts.jade.
router.get('/accounts', function(req, res, next) {

org.query({ query: "Select Id, Name, Type, Industry,
                    Rating From Account Order
                    By LastModifiedDate DESC" })
  .then(function(results){
    res.render('index-accounts', { records: results.records });
  });

});
  1. Create a file list-accounts.jade under views folder. This will be the view whch shows the list of accounts fetched from the server.
extends ../node_modules/jade-bootstrap/layouts/navbar-fixed-force

append body

  +navbar-fixed("","navbar", "inverse")
    +nav_item("/accounts","active") Accounts
    +nav_item("/contacts") Contacts
    +nav_item("#") Opportunities

  .container
    div(style='padding-bottom:100px;')

    div
      form.form-signin(action="/create-account", method="get")
         button.btn.btn-large.btn-primary(type="submit",
                                          style='margin:1px;') Create Account
      table.table.table-striped.table-hover.span12
        thead
          tr
            th Id
            th Name
            th Type
            th CreatedDate
        tbody
          - each r in records
            tr
             form.form-signin(action="/delete-account", method="post")
              td
                 input.input-block-level(type="text",
                                         name="id",
                                         value=r.get('id'), readonly
                                         )
              td= r.get('Name')
              td= r.get('Type')
              td= r.get('CreatedDate')
              td
                button.btn.btn-large.btn-primary(type="submit",
                                                 style='margin:1px;') Del

Screenshot below shows the List of Accounts at runtime

../_images/list_accounts.png

Create Account

Create Account is triggered from the button we created above in index-accounts.jade

  1. Render create-account form

    router.get('/create-account', function(req, res, next) {
      res.render('create-account', { title: 'Create Account'});
    });
    
  2. Create Account Form create-account.jade

    extends ../node_modules/jade-bootstrap/layouts/navbar-fixed-force
    
    append body
    
      +navbar-fixed("Force.com Sample","navbar", "inverse")
        +nav_item("#","active") Accounts
        +nav_item("#") Contacts
        +nav_item("#") Opportunities
    
      .container
        div(style='padding-bottom:100px;')
    
        div(style='padding:10px;')
         form.form-signin(action="/create-account", method="post")
          h3 Create Account
          br
          input.input-block-level(type="text", name="name",
                                  placeholder="Name", style='margin:10px;')
          br
          input.input-block-level(type="text", name="industry",
                                  placeholder="Industry", style='margin:10px;')
          br
          input.input-block-level(type="text", name="type",
                                  placeholder="Type", style='margin:10px;')
          br
          button.btn.btn-large.btn-primary(type="submit",
                                           style='margin:10px;') Create
    
  3. On pressing the Create button folloing code in routes/index.js is executed

    router.post('/create-account', function(req, res, next) {
           var acc = nforce.createSObject('Account');
           acc.set('Name', req.body.name);
           acc.set('Industry', req.body.industry);
           acc.set('Type', req.body.type);
    
    
           org.insert({ sobject: acc })
             .then(function(account){
               res.render('message', {title: 'Account Created: ' + String(account.id) });
             })
    });
    

Screenshot below shows the Form for create account

../_images/create_account.png

Delete Account

  1. You can see the Del Button in every row of Accounts table. This allows deletion of the Account. This triggers a call to REST endpoint /delete-contact.

    router.post('/delete-account', function(req, res, next) {
    
      var acc = nforce.createSObject('Account');
      acc.set('Id', req.body.id);
      console.log('id: %s', req.body.id);
      org.delete({ sobject: acc })
        .then(function(account){
          res.render('message', {title: 'Account Deleted: ' +  String(req.body.id) });
        });
    });
    
  2. On completion of Deletion image deleted Account ID is shown on the screen.

Run the App Locally

App can be run locally using the following command

$ npm start

Open the App at the url http://localhost:3000/

../_images/home.png

Contacts

Similary you can implement Create, Delete, List operations of Contacts.