Saturday, October 12, 2019
Wednesday, October 9, 2019
PDF Reader as a Salesforce Lightning Web Component
This is a Lightning web component based on PDF.js library to render a PDF document (an unencoded string representation of the PDF blob) inside an
iframe
.Check the code below for this component:
https://github.com/iamsonal/lwc-pdfReader
Tuesday, October 1, 2019
A basic Salesforce to Salesforce integration using REST API and OAuth
You can use a connected app to request access to Salesforce data on behalf of an external application. For a connected app to request access, it must be integrated with the Salesforce API using the OAuth 2.0 protocol.
1. Create a connected app in one of the Salesforce instances as below:
You will need to replace the callback URL after the completion of step 2.
2. Create an Auth Provider. Replace the consumer key and secret with the values.
Replace the callback URL in the connected app with the callback URL generated while creating this auth provider.
3. Create a named credential
4. Some Apex code
1. Create a connected app in one of the Salesforce instances as below:
You will need to replace the callback URL after the completion of step 2.
2. Create an Auth Provider. Replace the consumer key and secret with the values.
Replace the callback URL in the connected app with the callback URL generated while creating this auth provider.
3. Create a named credential
4. Some Apex code
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Cross_Org_Report/services/data/v45.0/query?q=select+Email,FirstName,LastName+from+contact');
req.setMethod('GET');
Http http = new Http();
HTTPResponse response = http.send(req);
return response.getBody();
Sunday, August 18, 2019
LWC: Implementing Service Components
A service component is a component that provides an API for a set of functionalities. Ideally, the service should be specialized, generic and reusable. Also, it does not have a markup, i.e. it is not visible by default.
Creating a custom service simplifies component’s code and help reduce code duplication. This in turns makes the code more robust and facilitates maintenance.
To develop a custom service component for my Account object, I have created an
accountService
component and exposed the below services:searchAccount
: it accepts a search key and returns the list of accounts matching the keygetAccounts
: this returns a list of 5 accounts
accountComponent
which is consuming the services like below:Please see the below repo for the code:
https://github.com/iamsonal/lwc-service
References:
https://developer.salesforce.com/blogs/2018/08/implement-and-use-lightning-service-components.html
Saturday, August 17, 2019
LWC: Modularizing Code using Singleton pattern
Imagine that we have a custom LWC component, which we drag-and-drop onto a Lightning page in Lightning App Builder. This component has 2 design attributes for First Name and Last Name. We need a way to access these values from any component without communicating down the containment hierarchy. Setting the public properties of child components becomes a tedious job if there are nested components.
To solve this issue, we can use the Singleton Pattern, which states that the number of instances of an object must be restricted to one only, hence the "single" in Singleton. The intent of the Singleton is ensuring a class has only one instance, and providing a global point of access to it.
For the sake of simplicity, I have created 2 components
component1
and component2
where component2
is the child of component1
. I need to access the design attribute values of the parent component from the child component. In this example, we are storing the design attribute values in a single central place, sharedData
component, written in the Singleton pattern.customLabels
using Javascript classes to access the custom labelsPlease see the below repo for the code:
https://github.com/iamsonal/lwc-singleton
Saturday, August 10, 2019
LWC: Modal implementation
Check the code in the below repo for the modal implementation in LWC:
https://github.com/iamsonal/lwc-modal
Notes:
- If you want to hide the close icon, then set the
hide-close
property totrue
like below:
<!-- modalContainer.html -->
<template>
<c-modal name="Modal Name" title="Modal Title" hide-close>
</c-modal>
</template>
- Similarly, if you want to display a large modal, then set the
is-large
property totrue
like below:
<!-- modalContainer.html -->
<template>
<c-modal name="Modal Name" title="Modal Title" hide-close is-large>
</c-modal>
</template>
<c-modal name="Modal Name" title="Modal Title" >
<!-- Unnamed Slot -->
<p>This is some content</p>
<!-- Named Slot -->
<div slot="footer" style="display: inline;">
<lightning-button label="Close" variant="neutral" onclick={handleCancelModal}></lightning-button>
</div>
</c-modal>
style-class
property to apply a custom CSS in the modal.Saturday, July 13, 2019
LWC: Override CSS of standard Lightning Web Components
Recently, I got a requirement where I had to override the CSS of
Shadow Dom have their own little kingdom and cannot be styled from outside, except if they would provide some options to do so. Currently, it's not possible to style standard Lightning Web Components;
I am providing a hacky workaround to get the desired results. I added the below code in my
and this is how it looks:
UPDATE:
It seems there is a cleaner approach as suggested by pdebaty: loading CSS using
lightning-card
component, specifically to change the background colour of the header of the card component.Shadow Dom have their own little kingdom and cannot be styled from outside, except if they would provide some options to do so. Currently, it's not possible to style standard Lightning Web Components;
I am providing a hacky workaround to get the desired results. I added the below code in my
helloExpressions
component:renderedCallback() {
const style = document.createElement('style');
style.innerText = `c-hello-expressions .slds-card__header {
background-color: #54C2B2;
}`;
this.template.querySelector('lightning-card').appendChild(style);
}
and this is how it looks:
UPDATE:
It seems there is a cleaner approach as suggested by pdebaty: loading CSS using
loadStyle
...lol. You can go through the StackExchange article to understand more in details.Saturday, June 1, 2019
LWC: Retrieving custom labels dynamically
To access labels in a Lightning web component, import them from the
@salesforce/label
scoped module.import greeting from '@salesforce/label/c.greeting';
import salesforceLogoDescription from '@salesforce/label/c.salesforceLogoDescription';
As far as the official documentation goes, it is clear that one needs to know the name of a custom label at design time; it is impossible to evaluate the value at runtime by knowing their name.
Arteezy and Sfdcfox commented in this StackExchange post that you can use Salesforce inspector and tooling API to retrieve the custom labels using this query:
SELECT Id, Name, Value FROM CustomLabel
Based on this, I have created an LWC service component
customLabelService
, which will retrieve all the custom labels and store it as an object on client-side. You can use this component as below:1. As per this StackExchange post, there is no way of getting a valid API-capable sessionId from a Lightning component because sessions obtained from Apex used by a Lightning component are not API enabled. That's why as a workaround, I have created a VF page, and
getSessionIdFromVFPage
method in CustomLabelController
class to retrieve the sessionId. You can also refer to this post to know more in details.2. If there is a requirement where you need to retrieve all the labels with a known prefix, then change the resourcePath (URI) to below:
/services/data/v46.0/tooling/query/?q=Select+id,Name,Value+from+CustomLabel+WHERE+Name+LIKE+'OAuthModal%25'
where the prefix is
OAuthModal
. I checked in Workbench, and this works fine, but you will need to tweak the code to pass the prefix.3. As per this StackExchange post, there are two objects that represent labels,
CustomLabel
and ExternalString
. So you can also use tooling API to fetch the labels from ExternalString
using the below query:SELECT Id, Name, Value, Language FROM ExternalString
UPDATE:
Please refer the code of this project from the link below:
https://github.com/iamsonal/Custom-Labels
Saturday, March 9, 2019
Javascript: Array Helper Methods
forEach()
forEach() is usually used as a replacement for traditional for-loop. Lets add an array of numbers. In classic Javascript, this is how you will write the code:var numbers = [11, 12, 13, 14, 15];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
Using forEach helper method, the code will be something like below:
var numbers = [11, 12, 13, 14, 15];
var sum = 0;
numbers.forEach(function(number) {
sum += number;
});
console.log(sum);
The iterator function doesn't have to be an anonymous function. We can declare a function separately and then pass it in forEach as below:
var numbers = [11, 12, 13, 14, 15];
var sum = 0;
function addNumbers(number) {
sum += number;
}
numbers.forEach(addNumbers);
console.log(sum);
map()
Write a loop that iterates over a list of numbers, doubles the value of each number in the array and then pushes the doubled number into a new array.In classic JS, this is how the code will look like:
var numbers = [11, 12, 13, 14, 15];
var double = [];
for (var i = 0; i < numbers.length; i++) {
double.push(numbers[i] * 2);
}
console.log(double);
Now we will refactor the code above to use the map helper.
var numbers = [11, 12, 13, 14, 15];
var double = numbers.map(function(number) {
return number * 2;
});
console.log(double);
You can also reformat the code like below:
var numbers = [11, 12, 13, 14, 15];
var doubleFn = (num) => num * 2;
var double = numbers.map(doubleFn);
console.log(double);
One of the most common uses of map is collecting properties of an array of object. Check the code below:
const persons = [
{firstName:"John", lastName:"Doe"},
{firstName:"Mike", lastName:"Crusoe"},
];
const firstNames = persons.map(person => person.firstName);
console.log(firstNames);
filter()
We will be filtering out persons who are working in Finance department. This is how we will write code in classic Javascript:var persons = [
{firstName:"John", lastName:"Doe", age:46, department:"Finance"},
{firstName:"Mike", lastName:"Crusoe", age:40, department:"Finance"},
{firstName:"Mary", lastName:"Jane", age:30, department:"HR"}
];
var filteredPersons = [];
for (var i = 0; i < persons.length; i++) {
if (persons[i].department === "Finance") {
filtered.push(persons[i]);
}
}
console.log(filteredPersons);
Now we will refactor the code above to use the filter helper.
const persons = [
{ firstName: "John", lastName: "Doe", age: 46, department: "Finance" },
{ firstName: "Mike", lastName: "Crusoe", age: 40, department: "Finance" },
{ firstName: "Mary", lastName: "Jane", age: 30, department: "HR" }
];
const filteredPersons = persons.filter(person => person.department === 'Finance');
console.log(filteredPersons);
find()
This method will return only first element where callback function returns true; it don't process other elements.We will search for user whose name is Mike. This is how we will write code in classic Javascript:
var users = [
{name:"John"},
{name:"Mike"},
{name:"Mary"}
];
var user;
for (var i = 0; i < users.length; i++) {
if (users[i].name === 'Mike') {
user = users[i];
break;
}
}
console.log(user);
Now we will refactor the code above to use the find helper.
const users = [
{name:"John"},
{name:"Mike"},
{name:"Mary"}
];
const user = users.find(user => user.name === 'Mike');
console.log(user);
Friday, March 8, 2019
Javascript: Arrow functions and this
Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:
Even if I use
In the below example, when using traditional function,
In order to get the greeting message using the traditional function, there are several ways to keep reference to
or bind with
(a, b) => a + b // implicitly returning a + b
(a, b) => { // explicitly returning a + b
return a + b;
}
a => a * a // omit () when there is one parameter
() => 2 // () mandatory when there are no parameters
(a, b) => { // explicitly returning JS object
return {
a1: a, b1: b
}
}
(a, b) => ({ // implicitly returning JS object
a1: a, b1: b
})
An arrow function does not have its ownIn the example below, when using traditional function,this
.this
in arrow functions is always statically defined by the surrounding lexical scope.
this
refers to the num
object, whereas when using arrow notation, this
is pointing to the global object. Arrow functions doesn't have its own this
, and so this
refers to outer scope, and outer scope for num
object is the window
object.Even if I use
call()
method, result is the same.In the below example, when using traditional function,
this
refers to the global object, whereas using arrow function, we get the desired result.In order to get the greeting message using the traditional function, there are several ways to keep reference to
this
object inside of setTimeOut function. You can create a self
variable like below:const str = {
value: 'Delayed greeting',
greet: function() {
const self = this;
setTimeout(function() {
console.log(self.value);
}, 2000)
}
};
str.greet();
or bind with
this
like below:const str = {
value: "Delayed greeting",
greet: function() {
setTimeout(
function() {
console.log(this.value);
}.bind(this),
2000
);
}
};
str.greet();
It is not possible to use arrow function expression as a function constructor and create new objects from it.
Monday, March 4, 2019
LWC: Fetch picklist values
<!-- fetchPicklistValues.html -->
<template>
<lightning-card title="WireGetPicklistValues" icon-name="custom:custom67">
<template if:true={picklistValues.data}>
<div class="slds-m-around_medium">
<template for:each={picklistValues.data.values} for:item="item">
<lightning-input
key={item.value}
label={item.label}
data-value={item.value}
type="checkbox"
onchange={handleCheckboxChange}
></lightning-input>
</template>
</div>
</template>
</lightning-card>
</template>
// fetchPicklistValues.js
import { LightningElement, wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import TYPE_FIELD from '@salesforce/schema/Account.Type';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
export default class FetchPicklistValues extends LightningElement {
@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
objectInfo;
@wire(getPicklistValues, {
recordTypeId: '$objectInfo.data.defaultRecordTypeId',
fieldApiName: TYPE_FIELD
})
picklistValues;
handleCheckboxChange(event) {
console.log(event.target.dataset.value);
console.log(event.target.checked);
}
}
As per documentation, use
getPicklistValues
wire adapter (from lightning/uiObjectInfoApi module) to fetch picklist values for a specified field.Parameters:
recordTypeId
—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from getObjectInfo or getRecordUi.fieldApiName
—(Required) The API name of the picklist field on a supported object.propertyOrFunction
—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with @wire, the results are returned in an object with a data property and an error property.
Sunday, March 3, 2019
Lightning Web Components: A Tale of Two DOM's
The shadow DOM is a subtree that branches off the DOM (light DOM). It hides away the complexity of components from the rest of the page. It has actually been around for quite a while. In fact, all of these elements utilize the shadow DOM to hide their complex markup and styling away.
<input type="range" />
<video controls width="250"></video>
<input type="date" />
Because of the new concept of shadow DOM, we need to avoid the confusion between the DOM you knew before and this new shadow DOM. So you are going to see the term light DOM used to describe the DOM you have been familiar with and working with all these years. But before we dive into the shadow DOM, here's one more term, the logical DOM. So the logical DOM is an umbrella term, so the light DOM and shadow DOM together are a part of logical DOM.
To understand shadow DOM, let’s look at the HTML5 <video> element, which is a custom element with a shadow DOM. Because Show user agent shadow DOM is enabled in Chrome Developer Tools, you see the #shadow-root node and its child elements, which make up the shadow DOM. If you disable this option, you would see only the <video> tag, and none of its children.
There are a variety of terms that we need to understand when working with the shadow DOM.
- Shadow Host: It is the element in the light DOM that is hosting the shadow DOM. So the shadow host, in this case, is the video tag, and it hosts the shadow root.
- Shadow Root: It is labelled in Chrome dev tools with #shadow-root, and is the root node of the shadow tree, encapsulating a DOM subtree. All this markup within the shadow root is shadow DOM. You can also see a nested shadow tree here, which is also known as a DOM subtree. So one DOM subtree can end up hosting another DOM subtree
- Shadow Boundary: It encapsulates styling rules that are defined within a given piece of shadow DOM. So in other words, a CSS selector that's applied in the shadow DOM doesn't apply to other elements outside of shadow DOM and vice versa. This is because styles in the shadow DOM do not cross over the shadow boundary. The shadow boundary exists at the shadow root. To clarify, the shadow boundary is a concept and is merely a term used to describe the boundary between the light DOM and shadow DOM.
- Select shadow host, which is an element in the light DOM that will wrap the shadow root.
- Create a shadow root
- Add elements to the shadow DOM using the same methods that you use to append elements to the light DOM: innerHTML and appendChild
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h1 { color: red; }
</style>
</head>
<body>
<h1>Hello World from the light DOM</h1>
<div id="host"></div>
<template>
<h1>Hello World from the shadow DOM</h1>
</template>
<script>
var template = document.querySelector('template');
var host = document.getElementById('host');
var root = host.attachShadow({mode: 'open'});
root.appendChild(document.importNode(template.content, true));
// Only going to get a reference to the light DOM
console.log(document.querySelectorAll('h1'));
// Only going to get a reference to the shadow DOM. For multiple pieces of shadow DOM in the page,
// you need to get the shadow root that is appropriate for the element that you are trying to target
console.log(root.querySelectorAll('h1'));
</script>
</body>
</html>
Lightning Web Components
The shadow DOM for a Lightning web component is created automatically. The component author doesn’t have to implement it (no need to use the attachShadow() or appendChild() methods). Also since Lightning web components don’t use the native shadow DOM yet, you can’t view their shadow DOM in Chrome Developer Tools. Even if you enable Show user agent shadow DOM, you don’t see the shadow DOM.Resources:
https://medium.com/front-end-weekly/the-rise-of-shadow-dom-84aa1f731e82
Monday, January 28, 2019
Salesforce Apex: Regular Expressions
Assume that you receive an email, and your task is to extract all the URLs present in the email body. Copy and paste is a tedious job, right? Using regex script, you can save yourself from the manual work.
You can refer the following code to extract all the URLs from an incoming email.
global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {
public static final String REGEX_URL = '(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?«»“”‘’]))';
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String plainTextBody = email.plainTextBody;
Matcher m = Pattern.compile(REGEX_URL).matcher(plainTextBody);
while (m.find()) {
System.debug(m.group());
}
...
...
...
}
}
Similarly you can use the following regex expression for email addresses:
String REGEX_EMAIL = '(?:[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])';
and this one for phone numbers
String REGEX_PHONE = '(?:(?:\\+?([1-9]|[0-9][0-9]|[0-9][0-9][0-9])\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([0-9][1-9]|[0-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?';
Sunday, January 27, 2019
Javascript: Preventing Object Modification
All objects you create are extensible by default, meaning new properties can be added to the object at any time. By setting Extensible attribute on an object to false, you can prevent new properties from being added to an object. There are three different ways to accomplish this.
Preventing Extensions
One way to create a nonextensible object is with Object.preventExtensions(). In the code below, as person1 is nonextensible, the sayName() method is never added to it.var person1 = {
name: "Nicholas"
};
console.log(Object.isExtensible(person1)); // true
Object.preventExtensions(person1);
console.log(Object.isExtensible(person1)); // false
person1.sayName = function() {
console.log(this.name);
};
console.log("sayName" in person1); // false
Sealing Objects
You can use the Object.seal() method on an object to seal it. A sealed object is nonextensible, and all of its properties are nonconfigurable. That means not only can you not add new properties to the object, but you also can’t remove properties or change their type.var person1 = {
name: "Nicholas"
};
console.log(Object.isExtensible(person1)); // true
console.log(Object.isSealed(person1)); // false
Object.seal(person1);
console.log(Object.isExtensible(person1)); // false
console.log(Object.isSealed(person1)); // true
person1.sayName = function() {
console.log(this.name);
};
console.log("sayName" in person1); // false
person1.name = "Greg";
console.log(person1.name); // "Greg"
delete person1.name;
console.log("name" in person1); // true
console.log(person1.name); // "Greg"
var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable); // false
Freezing Objects
If an object is frozen, you can’t add or remove properties, you can’t change properties’ types, and you can’t write to any data properties. In essence, a frozen object is a sealed object where data properties are also read-only. Frozen objects can’t become unfrozen, so they remain in the state they were in when they became frozen.var person1 = {
name: "Nicholas"
};
console.log(Object.isExtensible(person1)); // true
console.log(Object.isSealed(person1)); // false
console.log(Object.isFrozen(person1)); // false
Object.freeze(person1);
console.log(Object.isExtensible(person1)); // false
console.log(Object.isSealed(person1)); // true
console.log(Object.isFrozen(person1)); // true
person1.sayName = function() {
console.log(this.name);
};
console.log("sayName" in person1); // false
person1.name = "Greg";
console.log(person1.name); // "Nicholas"
delete person1.name;
console.log("name" in person1); // true
console.log(person1.name); // "Nicholas"
var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable); // false
console.log(descriptor.writable); // false
Monday, January 21, 2019
Javascript modules, named and default exports
Take this code where we have multiple classes defined in the same file.
class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
class Teacher extends Person {
constructor(name, degree) {
super(name);
this.degree = degree;
}
teach() {
console.log("Teach");
}
}
const teacher = new Teacher("John", "MA");
teacher.walk();
If we can split this code across multiple files, we call it modularity, and each file is known as module. So let's modularize this code as below so that each class will be in a separate file. The objects we define in a module are private by default. To make it public, we use the
export
keyword, and to use it we use the import
keyword.person.js
export class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
teacher.js
import { Person } from "./person";
class Teacher extends Person {
constructor(name, degree) {
super(name);
this.degree = degree;
}
teach() {
console.log("Teach");
}
}
index.js
import { Teacher } from "./Person";
const teacher = new Teacher("John", "MA");
teacher.walk();
The way we have used the export keyword, we call it named exports. To use default exports, modify
person.js
as follows:export default class Person {
constructor(name) {
this.name = name;
}
walk() {
console.log("Walk");
}
}
and in
teacher.js
file, import Teacher
module as below:import Person from "./person";
...
...
Wednesday, January 9, 2019
Javascript: Destructuring
Destructuring Objects
With destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data.
const person = {
first: "John",
last: "Doe",
links: {
social: {
twitter: "https://twitter.com/john.ca",
facebook: "https://facebook.com/johndoe"
},
web: {
blog: "https://johndoe.com"
}
}
};
const { twitter, facebook } = person.links.social;
Rename the variables as you destructure
const { twitter: tweet, facebook: fb } = person.links.social;
Set fallback or default value
const settings = { width: 300, color: "black" };
const { width = 100, height = 100, color = "blue", fontSize = 25 } = settings;
Destructuring arrays
const details = ["John Doe", 123, "johndoe.com"];
const [name, id, website] = details;
console.log(name, id, website);
Destructuring comma separated string
const data = "Basketball,Sports,90210,23,John,Doe,cool";
const [itemName, category, sku, inventory] = data.split(",");
Destructuring into Rest - an example using rest parameter
const team = ["John", "Harry", "Sarah", "Keegan", "Riker"];
const [captain, assistant, ...players] = team;
Swapping Variables with Destructuring
let inRing = "Hulk Hogan";
let onSide = "The Rock";
[inRing, onSide] = [onSide, inRing];
To make order of arguments independent, wrap these 3 arguments in , and then pass an object in tipCalc function so that it destructures the object.
function tipCalc({ total = 100, tip = 0.15, tax = 0.13 }) { return total + tip * total + tax * total; } const bill = tipCalc({ tip: 0.2, total: 200 }); console.log(bill);
What is we don't pass anything in tipcalc?
function tipCalcDefault({ total = 100, tip = 0.15, tax = 0.13 } = {}) { return total + tip * total + tax * total; } const newBill = tipCalcDefault(); console.log(newBill);
Javascript: Spread and Rest Operators
Rest Operator
Takes multiple things and packs it into a single array
function convertCurrency(rate, ...amounts) {
console.log(rate, amounts); // 1.5 [10, 20, 30]
}
convertCurrency(1.5, 10, 20, 30);
Can be used while destructuring into an array
const team = ["John", "Kait", "Lux", "Sheena", "Kelly"];
const [captain, assistant, ...players] = team;
console.log(captain, assistant, players);
Spread Operator
(3 dots in-front of an array or any iterable) Takes every single item from an iterable (that can loop over with for-of loop) and spread it into a new array
const featured = ["Deep Dish", "Pepperoni", "Hawaiian"];
const specialty = ["Meatzza", "Spicy Mama", "Margherita"];
const pizzas = [...featured, "veg", ...specialty];
Using above example, creating a new array fridayPizzas
const fridayPizzas = [...pizzas];
pizzas != fridayPizzas (shallow copy)
Spread string
const name = "john";
console.log([...name]); // ["j", "o", "h", "n"]
Remove an object from an array of objects
const comments = [
{ id: 209384, text: "I love your dog!" },
{ id: 523423, text: "Cuuute! 🐐" },
{ id: 632429, text: "You are so dumb" },
{ id: 192834, text: "Nice work on this wes!" }
];
const id = 632429;
const commentIndex = comments.findIndex(comment => comment.id === id);
const newComments = [
...comments.slice(0, commentIndex),
...comments.slice(commentIndex + 1)
];
console.log(newComments);
Spreading into a function
const inventors = ["Einstein", "Newton", "Galileo"];
const newInventors = ["Musk", "Jobs"];
inventors.push(...newInventors); // and not inventors.push(newInventors);
console.log(inventors);
One more example
const name = ["John", "Doe"];
function sayHi(first, last) {
alert(`Hey there ${first} ${last}`);
}
sayHi(...name);
Saturday, January 5, 2019
Creating named credential with API key
1. Create a named credential like below specifying any username. Make sure that you have checked "Allow Merge Fields in HTTP Header" and unchecked "Generate Authorization Header" options.
2. Specify the API key in your Apex code using {!$Credential.Password} merge field.
2. Specify the API key in your Apex code using {!$Credential.Password} merge field.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:AnonAPI');
req.setHeader('APIKEY', '{!$Credential.Password}');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
Friday, January 4, 2019
Javascript: Execution Context
Execution Context allows the Javascript engine to manage the complexity of interpreting and running the code. Every execution context has 2 phases: Creation phase and Execution phase.
The first execution context, the Global Execution Context, gets created when the Javascript engine runs your code. In this execution context,
- Global object gets created, which is the window object.
this
object gets created, pointing to the window object.- We set up memory space for variables and functions.
- All the variables declarations are assigned a default value of undefined (this is hoisting), while the function declaration is put entirely into memory.
Invoking a function creates the Function Execution Context. It is precisely the same as the global execution context except that instead of creating a global object, an arguments object gets created. Take, for example, the code below:
function fn() {
console.log(arguments);
}
fn(x, y);
Here arguments is an array-like object for all of the arguments passing inside of this function, and a keyword in Javascript.
Now anytime a function is invoked, a new execution context is created and added to the execution stack. Whenever a function is finished running through both the creation phase and the execution phase, it gets popped off the execution stack.
Anytime you pass a variable to a function, that variable during the creation phase of a function execution context is going to be put in the variable environment of the current execution context as if they are local variables to the execution context. So for the code below
var name = 'John';
var handle = '@johndoe';
function getURL (handle) {
var url = 'https://facebook.com/';
return url + handle;
}
getURL(handle);
during the creation phase of getURL function, the value of url is undefined, while the value of handle is
@johndoe
as the variable is passed to a function. The value of arguments object during creation phase is {0:"@johndoe", length:1}
.If the Javascript engine can't find a variable local to the function's execution context, it will look to the nearest parent execution context for that variable. This process will continue all the way up until the engine reaches the global execution context. If the global execution context doesn't have the variable, then it will throw a reference error because that variable doesn't exist anywhere up to the scope chain or the execution context chain.
var name = 'John';
function logName() {
console.log(name);
}
logName();
Now let's look at the code below:
var count = 0;
function makeAdder(x) {
return function inner(y) {
return x + y;
};
}
var add5 = makeAdder(5);
count += add5(2);
Here we have a function nested inside a function (inner inside of makeAdder), and whenever that happens, the inner function is going to create a closure over the outer function's execution context. This is because later on when inner function is invoked, it needs to have access to any of the variables declared in the parent function's execution context even though that parent function's execution context has been removed from the stack. So the variables inside of this closure execution context are same as the variables that were in the makeAdder execution context. This whole concept is known as closure.
Subscribe to:
Posts (Atom)