SkillAgentSearch skills...

Forcejs

Micro library to use the Salesforce REST APIs in JavaScript Apps

Install / Use

/learn @ccoenraets/Forcejs
About this skill

Quality Score

0/100

Category

Sales

Supported Platforms

Universal

README

ForceJS - JavaScript Toolkit for Salesforce APIs

ForceJS is a micro-library that makes it easy to use the Salesforce REST APIs in JavaScript applications. ForceJS allows you to easily authenticate with Salesforce using OAuth, and to manipulate Salesforce data using a simple API.

The main target of ForceJS are:

  • Client-side JavaScript applications deployed on your own server (Heroku or elsewhere)
  • Hybrid mobile apps built with Apache Cordova and the Salesforce Mobile SDK

Applications deployed inside a Salesforce instance (Visualforce Page or Lightning Components) can use one of the data access utilities built into the Salesforce Platform instead: JavaScript Remoting, Remote Objects, Lightning Data Service, etc.

Built on ECMAScript 6

Modern JavaScript applications now use ECMAScript 6 (aka ECMAScript 2015) and beyond. The current version of modern frameworks (such as React, Angular 2, and Ionic 2) are also built on top of ECMAScript 6 and beyond. To support modern application development, and to integrate nicely with these frameworks, ForceJS is now built on top of ECMAScript 6 as well.

Compatible with ECMAScript 5

The ECMAScript 6 source files are compiled into an ECMAScript 5 compatible version. The ECMAScript 5 compatible files are available in the dist directory. The ECMAScript 5 files support the Universal Module Definition (UMD) format. In other words, they can be used with AMD or CommonJS module loaders as well as globally using the force.OAuth and force.DataService variables.

The original ECMAScript 5-only version of forcejs is still available in the es5 branch of this repository. The es5 branch is no longer actively developed.

Key Characteristics

  • No dependency
  • Loaded as an ECMAScript 6 module
  • Asynchronous calls return ECMAScript 6 promises
  • Complete OAuth login workflow (User Agent)
  • Works transparently in the browser and in Cordova using the Salesforce Mobile SDK OAuth plugin
  • Automatically refreshes OAuth access_token (if available) on expiration
  • Tightly integrated with force-server, a local development server that works as a proxy and a local web server to provide a streamlined developer experience
  • Simple API to manipulate data (create, update, delete, upsert)
  • Supports connections to multiple instances of Salesforce in the same application
  • Works with modern JavaScript frameworks: React, Angular 2, Ionic 2, etc.

Modular

ForceJS is built on a modular architecture. It currently includes two modules:

  • forcejs/oauth: A module that makes it easy to authenticate with Salesforce using the OAuth User Agent workflow
  • forcejs/data-service: A module that makes it easy to access data through the Salesforce APIs

forcejs/oauth and forcejs/data-service are typically used together in an application, but you can use them separately. For example, you could use forcejs/oauth by itself if all you need is a Salesforce access token (Lightning Out use cases). Similarly, you could use forcejs/data-service by itself if you already have an access token, and all you need is a simple library to access the Salesforce APIs.

Browser and Cordova Abstraction

ForceJS can be used to develop browser-based apps or hybrid mobile apps using the Salesforce Mobile SDK and Apache Cordova. If you develop a hybrid application using the Salesforce Mobile SDK, you often switch back and forth between running the app in the browser and on device. Developing in the browser is generally faster and easier to debug, but you still need to test device-specific features and check that everything runs as expected on the target platforms. The problem is that the configuration of OAuth and REST is different when running in the browser and on device. Here is a summary of the key differences:

<table> <tr><td></td><td><strong>Browser</strong></td><td><strong>Mobile SDK</strong></td></tr> <tr><td>Requires Proxy</td><td>Yes(*)</td><td>No</td></tr> <tr><td>OAuth</td><td>Window Popup</td><td>OAuth Plugin</td></tr> </table>

(*) Starting in the Spring 15 release, some Salesforce REST APIs (like Chatter and sobjects) support CORS. To allow an app to make direct REST calls against your org, register the app domain in Setup: Administer > Security Controls > CORS.

ForceJS abstracts these differences and allows you to run your app in the browser and on device without code or configuration changes.

ECMAScript 6 Usage

import {OAuth, DataService} from 'forcejs';

let oauth = OAuth.createInstance();
oauth.login().then(oauthResult => DataService.createInstance(oauthResult));

let loadContacts = () => {
    let service = DataService.getInstance();
    service.query('select id, Name from contact LIMIT 50')
        .then(response => {
            let contacts = response.records;
            // do something with contacts
    });
}

If you are only using one of the forcejs submodules (either oauth or data), the following import syntax is recommended to make sure the compiled version does not include the module you don't use if your build tool doesn't support tree shaking:

import OAuth from 'forcejs/oauth';
//or
import DataService from 'forcejs/data-service';

Because current browsers don't yet support all the ECMAScript 6 features, you need to use a build tool to compile (transpile) your ECMAScript 6 code to ECMAScript 5 compatible code, and provide the module loading infrastructure. Webpack, Browserify, and Rollup are popular options. Webpack instructions are provided in the Quick Start sections below. Frameworks like React, Angular 2, and Ionic 2 already come with a build process. If you are using these frameworks, no additional step is necessary.

ECMAScript 5 Usage

Use the ECMAScript 5 compatible files available in the dist directory.

<script src="force.all.js"></script>
<script>
    var oauth = force.OAuth.createInstance();
    oauth.login().then(function(oauthResult) {
        force.DataService.createInstance(oauthResult);    
    });

    function loadContacts() {
        var service = force.DataService.getInstance();
        service.query('select id, Name from contact LIMIT 50')
            .then(function(response) {
                var contacts = response.records;
                // do something with contacts
            });
    }
</script>

If you are only using one of the forcejs modules (either oauth or data), the following syntax is recommended to avoid including modules you don't use:

<script src="force.oauth.js"></script>
// or
<script src="force.data-service.js"></script>

var oauth = force.OAuth.createInstance();
// or
var service = force.DataService.createInstance(oauthResult);

Quick Start 1: Simple Browser App

  1. Create a new directory for your project, navigate (cd) to that directory, and type the following command to initialize a project that uses the npm package manager (accept all the default values):

    npm init
    
  2. Type the following command to install forcejs:

    npm install forcejs --save-dev
    
  3. Type the following command to install the force-server development server:

    npm install force-server --save-dev
    
  4. Type the following command to install Webpack and Babel:

    npm install babel-core babel-loader babel-preset-es2015 webpack --save-dev
    
  5. Using your favorite editor, open package.json and modify the scripts section as follows:

    "scripts": {
        "webpack": "webpack",
        "start": "force-server"
    },
    
  6. In your project's root directory, create a file named webpack.config.js:

    var path = require('path');
    var webpack = require('webpack');
    
    module.exports = {
        entry: './app.js',
        output: {
            filename: 'app.bundle.js'
        },
        module: {
            loaders: [
                {
                    test: /\.js$/,
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015']
                    }
                }
            ]
        },
        stats: {
            colors: true
        },
        devtool: 'source-map'
    };
    
  7. In your project's root directory, create a file named index.html:

    <!DOCTYPE html>
    <html>
    <body>
        <h1>Forcejs Quick Start</h1>
        <ul id="contacts"></ul>
        <script src="app.bundle.js"></script>
    </body>
    </html>
    
  8. In your project's root directory, create a file named app.js:

    import {OAuth, DataService} from 'forcejs';
    
    let oauth = OAuth.createInstance();
    oauth.login()
        .then(oauthResult => {
            DataService.createInstance(oauthResult);
            loadContacts();
        });
    
    let loadContacts = () => {
        let service = DataService.getInstance();
        service.query('select id, Name from contact LIMIT 50')
            .then(response => {
                let contacts = response.records;
                let html = '';
                contacts.forEach(contact => html = html + `<li>${contact.Name}</li>`);
                document.getElementById("contacts").innerHTML = html;
        });
    }
    
  9. On the command line, type the following command to build your project:

    npm run webpack
    
  10. Type the following command to start the app in a browser:

    npm start
    

Quick Start 2: Hybrid Mobile App with Cordova and the Mobile SDK

  1. Install Cordova and the Salesforce Mobile SDK for the platform of your choice. For example, for iOS:

    npm install -g cordova forceios
    

    On a Mac, you may have to use sudo:

    sudo npm install -g cordova forceios
    
  2. Create a new mobile application:

    forceios create
    
  3. Answer the prompts a

Related Skills

View on GitHub
GitHub Stars176
CategorySales
Updated1y ago
Forks59

Languages

JavaScript

Security Score

65/100

Audited on Feb 12, 2025

No findings