Monday, October 30, 2017

JavaScript: Module Pattern


The module pattern is an object-creation pattern designed to create singleton objects with private data. The basic approach is to use an immediately invoked function expression (IIFE) that returns an object. An IIFE is a function expression that is defined and then called immediately to produce a result. That function expression can contain any number of local variables that aren’t accessible from outside that function. Because the returned object is defined within that function, the object’s methods have access to the data. Methods that access private data in this way are called privileged methods.

Here’s the basic format for the module pattern. In this pattern, an anonymous function is created and executed immediately. (Note the extra parentheses at the end of the function. You can execute anonymous functions immediately using this syntax.) That means the function exists for just a moment, is executed, and then is destroyed.
var yourObject = (function() {

   // private data variables

   return {
      // public methods and properties
   };

}());

The below code creates the person object using the module pattern. The age variable acts like a private property for the object. It can’t be accessed directly from outside the object, but it can be used by the object methods. There are two privileged methods on the object: getAge(), which reads the value of the age variable, and growOlder(), which increments age. Both of these methods can access the variable age directly because it is defined in the outer function in which they are defined.
var person = (function() {

   var age = 25;

   return {
      name: "Nicholas",

      getAge: function() {
         return age;
      },

      growOlder: function() {
         age++;
      }
   };

}());

console.log(person.name);   // "Nicholas"
console.log(person.getAge());   // 25

person.age = 100;
console.log(person.getAge());   // 25

person.growOlder();
console.log(person.getAge());   // 26

Revealing Module Pattern

There is a variation of the module pattern called the revealing module pattern, which arranges all variables and methods at the top of the IIFE and simply assigns them to the returned object. You can write the previous example using the revealing module pattern as follows:
var person = (function() {

   var age = 25;

   function getAge() {
      return age;
   }

   function growOlder() {
      age++;
   }

   return {
      name: "Nicholas",
      getAge: getAge,
      growOlder: growOlder
   };
   
}());
In this pattern, age, getAge(), and growOlder() are all defined as local to the IIFE. The getAge() and growOlder() functions are then assigned to the returned object, effectively "revealing" them outside the IIFE.

Source: The principles of object-oriented JavaScript by Nicholas

Reference: https://coryrylan.com/blog/javascript-module-pattern-basics
Share This:    Facebook Twitter

Sunday, October 29, 2017

Creating Lightweight Integrations with the Force.com REST API

REST API is simple access to Salesforce data and functionality via RESTful endpoints. It uses resource definition and HTTP verbs in a stateless fashion in order to communicate with the system.

Salesforce uses the OAuth protocol to allow users of applications to securely access data without having to reveal username and password credentials.

Before making REST API calls, you must authenticate the application user using OAuth 2.0. To do so, you’ll need to:
  • Set up your application as a connected app (that defines your application’s OAuth settings) in the Salesforce organization. When you develop an external application that needs to authenticate with Salesforce, you need to define it as a new connected app within the Salesforce organization that informs Salesforce of this new authentication entry point.
  • Determine the correct Salesforce OAuth endpoint for your connected app to use. OAuth endpoints are the URLs you use to make OAuth authentication requests to Salesforce.
  • Authenticate the connected app user via one of several different OAuth 2.0 authentication flows. An OAuth authentication flow defines a series of steps used to coordinate the authentication process between your application and Salesforce. Supported OAuth flows include:
    • Web server flow, where the server can securely protect the consumer secret.
    • User-agent flow, used by applications that cannot securely store the consumer secret.
    • Username-password flow, where the application has direct access to user credentials.
After successfully authenticating the connected app user with Salesforce, you’ll receive an access token which can be used to make authenticated REST API calls.

I have created a connected app "Sample Connected App". I have enabled OAuth Settings and entered a Callback URL. Depending on the OAuth flow, this is typically the URL that a user’s browser is redirected to, with either the authorization code or token, after successful authentication. The scopes under Selected OAuth Scopes refer to permissions given by the user running the connected app.

The Consumer Key and Consumer Secret is created which can be used to authenticate your application.

Click on Manage to see additional settings.

I have selected Relax IP Restrictions under IP Relaxation. Now lets go into Postman. I will be posting values, and for that I have to provide data in payload to get back the token. I will be using form-data as I will be providing a number of values. I have set the grant-type as password because I will be using username-password OAuth authentication flow (which is not ideal in most cases). The value for client_id will be the consumer key.

So this says that we have logged-in. Now lets try to get a list of accounts. Create a new request using the instance URL (INSTANCE_URL/services/data/v41.0/sobjects/account) that we received in the response earlier and for Authorization, concatenate Bearer and the access_token. Click the send button, and you will notice the response.

Similarly, you can check the responses for the below request URL:
INSTANCE_URL/services/data/v41.0/sobjects/account/describe
INSTANCE_URL/services/data/v41.0/sobjects/account/0017F00000I5zDl
INSTANCE_URL/services/data/v41.0/query?q=select+name+from+account

You can append .xml or .json to URI to get back the right representation. This works in most cases. If you are doing searches, it doesn't work in this way; in such cases, add "accept" header. The default is JSON if you are working in REST API. Now lets add Accept header to a standard HTTP header.

You can now remove Accept header and then append .xml to URI to get the same reponse.

Reference:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_authentication.htm
https://www.forcetalks.com/salesforce-topic/how-to-do-salesforce-to-salesforce-integration-using-rest-api/
Share This:    Facebook Twitter

Saturday, October 21, 2017

Lightning: Popups / Modal


Few months back, I created a single page application to create and edit broker details in a popup. The code for this app is provided in the github link provided in the reference section of this post.

The popup is invoked on click of New or Edit button. This popup gets created dynamically during runtime for which I have created a helper function displayModal.
displayModal : function(component, modalComponentName, modalProperties) {
    $A.createComponent(
        modalComponentName,
        modalProperties,
        function(newModal, status, errorMessage) {
            if (status === "SUCCESS")
                component.set("v.modal", newModal);
            else if (status === "INCOMPLETE")
                console.log("No response from server or client is offline.")
                else if (status === "ERROR")
                    console.log("Error: " + errorMessage);
        }
    );
}

This is how the helper function is called on click of New button
helper.displayModal(component, "c:BrokerPopup", {
    "broker": {'sobjectType':'Broker__c', 
               'Name':'', 
               'Mobile_Phone__c':'', 
               'Email__c':''
              }
});

To exit the popup, I am setting modal attribute of the component to null like below:
component.set("v.modal", null);

References:
Github link: https://github.com/iamsonal/BrokerApp
Share This:    Facebook Twitter

Friday, October 20, 2017

JavaScript Prototype


Every constructor function has a property on it called prototype which is an object. This prototype object has a property on it called constructor which points back to the original constructor function.

This prototype property can have methods and properties placed on it. These methods and properties are shared and accessible like any object that is created from that constructor function when the new keyword is used. Anytime an object is created using the 'new' keyword, a property called "__proto__" gets created, linking the object and the prototype property of the constructor function.

Lets define a constructor function Person with a property called name.
function Person(name) {
    this.name = name;
}

Functions are basically objects in Javascript. So Person happens to be a function object. Now when Javascript processes functions, it creates 2 objects. The second object that gets created for every function is the prototype object. To access this prototype object, it turns out that a property by the name 'prototype' gets created on function object that points to the prototype object. So to access this property, we will type Person.prototype as below:

This applies to all functions. Now I will create two objects from the constructor function using the new keyword.
var elie = new Person("Elie");
var colt = new Person("Colt");

Since I have used new keyword, a property has been added to each of these objects called __proto__ which points to the prototype object on the Person function constructor.
var elie = new Person("Elie");
var colt = new Person("Colt");

elie.__proto__ === Person.prototype
true

To validate this, we can set a custom property on Person.prototype and try to access it from elie.__proto__
So they are pointing to the same object.

Also, the prototype object has a property on it called constructor which points back to the original function.
Person.prototype.constructor === Person
true

Now let's write some code and use prototype object.
function Person(name, age) {
   this.name = name;
   this.age = age;
}

Person.prototype.eat = function() {
   console.log('I eat');
}

Person.prototype.sleep = function() {
   console.log('I sleep');
}

var elie = new Person('Elie', 20);

Check the output below in your browser console. You will note that Javascript will first search for sleep property in the elie object. If it isn’t there, then JavaScript will search for it in the object’s prototype.

Please note that you used the new keyword to create elie object. If you had invoked the Person function simply like below:
var elie = Person('Elie', 20);

then this is how the constructor should look like:
function Person(name, age) {
   var person = Object.create(Person.prototype);
   person.name = name;
   person.age = age;
   return person;
}

As of ES6, Javascript has now a class keyword. So we can refactor the code as follows:
class Person {
   constructor(name, age) {
      this.name = name;
   this.age = age;
   }

   eat() {
      console.log(this.name + ' eats.');
   }

   sleep() {
      console.log(this.name + ' sleeps.');
   }
}

var elie = new Person('Elie', 20);

This new way is just syntactical sugar over the existing way that we saw earlier. Now let's say that we want to get the prototype of elie. So use Object.getPrototypeOf() and pass in the specific instance of the object like below:
var proto = Object.getPrototypeOf(elie);

NOTE: Arrow functions don't have their own this keyword. As a result, arrow functions cannot be constructor functions, and if you try to invoke an arrow function using new keyword, it will give you an error. And so there is no prototype property in such functions.
const person = () => {}
const elie = new Person()  // Error: Person not a constructor

Person.prototype // undefined

Share This:    Facebook Twitter

Wednesday, October 18, 2017

Callback functions in JavaScript


Synchronous operation
const posts = [
    {title: "Post One", body: "This is post one"},
    {title: "Post Two", body: "This is post two"}
];

function createPost(post) {
    setTimeout(function () {
        posts.push(post);
    }, 2000);
}

function getPosts() {
    setTimeout(function () {
        let output = "";
        posts.forEach(function (post) {
            output += `<li>${post.title}</li>`;
        });
        document.body.innerHTML = output;
    }, 1000);
}

createPost({title: "Post Three", body: "This is post three"});

getPosts();

Asynchronous operation
const posts = [
    {title: "Post One", body: "This is post one"},
    {title: "Post Two", body: "This is post two"}
];

function createPost(post, callback) {
    setTimeout(function () {
        posts.push(post);
        callback();
    }, 2000);
}

function getPosts() {
    setTimeout(function () {
        let output = "";
        posts.forEach(function (post) {
            output += `<li>${post.title}</li>`;
        });
        document.body.innerHTML = output;
    }, 1000);
}

createPost({title: "Post Three", body: "This is post three"}, getPosts);

References:
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
https://houssein.me/javascript/2016/05/10/asynchronous-javascript-callbacks.html
http://callbackhell.com/
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top