[LWC] GraphQl in Salesforce


 

GraphQl:
GraphQL is a query language and runtime for APIs that enables declarative data fetching. In Salesforce, it provides a more efficient way to request and manage data compared to traditional methods.

Key advantages include:

  • Single endpoint for all data requests
  • Precise data retrieval (no over-fetching or under-fetching)
  • Reduced network overhead


Building Queries with GraphQL

GraphQL queries in Salesforce follow a structured format that allows precise data retrieval. Here's a basic query structure:

query {
  Account(where: { Name: { like: "Tech%" } }) {
    Name
    Industry
    BillingCity
  }
}

Implementing GraphQL in Lightning Web Components

Html:


<template>
    <lightning-card icon-name="custom:custom39" title="Accounts">
        <template lwc:if="{accountsData}">
            <div class="slds-var-m-around_medium">
                <template for:each="{accountsData}" for:item="account">
                    <p key="{account.Id}">
                        Name: {account.Name}, Phone: {account.Phone}
                    </p>
                </template>
            </div>
        </template>
    </lightning-card>
</template>

 Javascript:


import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';

export default class GraphqlContacts extends LightningElement {
    accountsData;
    @wire(graphql, {
        query: gql`
            query getAccounts{
                uiapi{
                    query{
                    Account(
                        where: { Name: { like: "United%" } }
                        first: 1
                    ){
                        edges{
                        node{
                            Id
                            Name{
                            value
                            }
                            Phone{
                            value
                            }
                        }
                        }
                    }
                    }
                }
            }`
    })
    graphqlcode({ errors, data }) {
        if(data){
        console.log('Data:', JSON.stringify(data));
           this.accountsData = data.uiapi.query.Account.edges.map((edge) => ({
                Id: edge.node.Id,
                Name: edge.node.Name?.value || 'No Name',
                Phone: edge.node.Phone?.value || 'No Phone',
            })) || []
        }
        if (errors) {
            console.error('GraphQL Error:', JSON.stringify(errors));
        }
    }
}

 Structure of response:

  • Query Name: getAccounts

  • Description:
    This query retrieves accounts from the Salesforce UI API where the account name starts with "United". It fetches the first account that matches the criteria.

  • Response Structure:

    uiapi: Contains the result of the query.

    -query: Contains the queried data.

    --Account: An array of account objects.

    ---edges: An array of edges containing account nodes.

    ----node: Represents an account.

    -----Id: The unique identifier of the account.

    -----Name: An object containing the account's name.

    ------value: The actual name of the account.

    -----Phone: An object containing the account's phone number.

    ------value: The actual Phone number of the account.

Actual Response:

{
  "data": {
    "uiapi": {
      "query": {
        "Account": {
          "edges": [
            {
              "node": {
                "Id": "001dL000006Nz7SQAS",
                "Name": {
                  "value": "United Oil &amp; Gas Corp."
                },
                "Phone": {
                  "value": "(212) 842-5500"
                }
              }
            }
          ]
        }
      }
    }
  },
  "errors": []
}

Comments