Open Source Lightning Web Components : Connect With Salesforce

In my last post we have created one dummy app using Open Source Lightning Web Components. Now in this post we will extend that component and will connect Open Source Lightning Web Components with Salesforce. We will fetch data from Salesforce and will display it on UI.

We will continue from where we left in my last post. To connect with Salesforce we need to install two more packages. jsforce is to query Salesforce data. It is a JavaScript Library utilizing Salesforce’s APIs. Dotenv Environment variables help us maintain configurability of the application without modifying the underlying code. Dotenv loads environment variables from a local .env file to allow an easy local development experience.
run below command (make sure you are in lwcOSDemo folder)
npm install jsforce dotenv

Folder Structure

Now we need a file Editor as we will create few files/folder to store the important information and configuration. For this we will use VScode editior.
In VSCode click on File > Open Folder and open the lwcOSDemo folder
This is how our folder structure (don’t worry if you don’t see some of the file in your folder I took this screenshot in the end.)

Lightning Web Components Open Source Folder Sturcture

Connection With Salesforce

First create a new file with name “.env”. Replace below information with your org details. Save this file in root folder.

SF_LOGIN_URL=https://login.salesforce.com
SF_USERNAME=YOUR_USERNAME
SF_PASSWORD=YOUR_PASSWORD
SF_TOKEN=YOUR_SECURITY_TOKEN

Now open the src> client >server >index.js file and paste below code.

const jsforce = require('jsforce');
require('dotenv').config();
const { SF_USERNAME, SF_PASSWORD, SF_TOKEN, SF_LOGIN_URL } = process.env;
if (!(SF_USERNAME && SF_PASSWORD && SF_TOKEN && SF_LOGIN_URL)) {
    console.error(
        'Cannot start app: missing mandatory configuration. Check your .env file.'
    );
    process.exit(-1);
}
const conn = new jsforce.Connection({
    loginUrl: SF_LOGIN_URL
});
conn.login(SF_USERNAME, SF_PASSWORD + SF_TOKEN, err => {
    if (err) {
        console.error(err);
        process.exit(-1);
    }
});
// eslint-disable-next-line no-undef
module.exports = app => {
    // put your app logic here
    app.get('/api/contacts', (req, res) => {
        const soql = `SELECT Id, FirstName, LastName, Email 
            FROM Contact LIMIT 10`;
            conn.query(soql, (err, result) => {
                if (err) {
                    res.sendStatus(500);
                } else if (result.records.length === 0) {
                    res.status(404).send('Contact not found.');
                } else {
                    const formattedData = result.records.map(conRecord => {                        
                        return {
                            id: conRecord.Id,
                            firstName: conRecord.FirstName,
                            lastName: conRecord.LastName,
                            email: conRecord.Email,
                        };
                    });
                    res.send({ data: formattedData });
                }
            });
    });
};

First we are using env file to read our parameters. Next we are making a connection with Salesforce. Make sure credentials are correct else you will get the silent error and will not get the expected result.
After that we are making a service in which we are making SOQL to get Contact records and returning the records. while the conn.login part will remain same, module.export we can modify that based on our use case.

DataModule to Access Data

Next we will create contactservice to read the data. In src> client> module> create new folder “data”> in that create new folder “contactServices”> In that create new file contactServices.js

const URL = '/api/contacts';
let contacts = [];
export const getContacts = () => fetch(URL)
  .then(response => {
    if (!response.ok) {
      throw new Error('No response from server');
    }
    return response.json();
  })
  .then(result => {
    contacts = result.data;
    return contacts;
  });

Here we are making request to our module and getting data from there. We will use this in our Lightning Web Component to access the data.

Now we are ready to display this data in our Lightning Web Component. We will use the existing component and modify that to display result. But you can also create a new component.
To create a new component go to src> client> module> create new folder with the component name> In new folder create one html file, one JS file and one css file, name same as component name.
We have used the below code to modify the existing component

app.html

<template>
    <header>
        <img src="resources/lwc.png" alt="App logo">
        <h2>Contact Records by NewsTechnologyStuff</h2>
    </header>
    <!-- Page code -->
    <main class="content">
        <div class="list">
            <input type="search" placeholder="Search contacts..."
                    oninput={searchdata} />

            <template for:each={contacts} for:item="cont">
                <a key={cont.id} class="contact">
                    <div>
                        <p class="title">{cont.firstName} {cont.lastName}</p>
                        <p class="icon email">{cont.email}</p>
                    </div>
                </a>
            </template>
        </div>
    </main>
</template>

app.js

import { LightningElement, track } from 'lwc';
import { getContacts } from 'data/contactService';

export default class App extends LightningElement {
    @track contacts = [];
    connectedCallback() {
        getContacts().then(result => {
        this.contacts = this.allContacts = result;
        });
    }

    searchdata(event) {
    const searchKey = event.target.value.toLowerCase();
    this.contacts = this.allContacts.filter(
        contact => contact.lastName.toLowerCase().includes(searchKey)
    );
  }
}

and this is how our final output will look.

Open Source Lightning Web Component Demo

You can find the complete code on my github repo.
So we have connected our app with Salesforce. We can easily use jsforce to perform DML operation as well. This also allow us to search locally. This is a basic component but we can easily use to develop advance level components and connect with Salesforce.

Did you like the post or do you have any question, let me know in comments section. Happy programming 🙂

Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.