Salesforce Rest API Limits Pie Chart Component

In this blog, I am going to show how to create a simple lightning component pie chat to visualize the salesforce limits by using salesforce rest API. I am going to use d3 js and d3pie to built the lightning component. refer more to d3 pie js here.

Step 1: Create a salesforce connected app as shown below. We need to create a named credential to authenticate the web service call. Go to setup –> create apps–> create a new connected app as shown below and save it to get consumer key and secret key. In this step use any URL as callback URL. later after confirmed the auth provides we will replace the callback URL from auth provider callback URL

After saving the connected app you will get consumer key and consumer secret which we will use to configure the Auth provides.

Step 2: Now we need to create an auth provide as shown below. Go to setup –> administration  –> Security control -> create a new Auth provide as shown below .

Replace the connected App callback URL with Auth provide callback URL

Step 3: Create a named credentials as shown below.

Step 4: Create an Apex Class

public class LimitsController {
    @AuraEnabled
    public static List<LimitsWrapper> getLimits(){
        List<LimitsWrapper> warpperlist = new List<LimitsWrapper>() ; 
        Http h = new Http();
        HttpRequest httpReq = new HttpRequest();
        httpReq.setMethod('GET');
        httpReq.setEndpoint('callout:REST_API1/services/data/v37.0/limits/');
        HttpResponse res = h.send(httpReq);
        System.debug('res'+res);
        Map<String, Object> root = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        System.debug('root'+root.keySet());
        for(String keys : root.keySet()){
            Map<String, Object> i = (Map<String, Object>)root.get(keys);
            Decimal percentage = Decimal.valueOf(String.valueOf(i.get('Remaining')))*100 /  Decimal.valueOf(String.valueOf(i.get('Max')));
            LimitsWrapper wrap = new LimitsWrapper();
            wrap.groupName = keys ; 
            wrap.usedPercentage = percentage.setScale(2) ; 
            warpperlist.add(wrap);
        }
        return warpperlist ;
    }
    public class LimitsWrapper{
        @AuraEnabled
        public Double usedPercentage {get; set;}
        @AuraEnabled
        public String groupName {get; set;}
    }
    
}

Step 5: Create a Lightning component

<aura:component implements="flexipage:availableForAllPageTypes"
                access="global"
                controller="LimitsController">
    <b> PIE CHART </b>
    <ltng:require scripts="{!join(',',
                           $Resource.d3pie + '/d3pie/d3.min.js',
                           $Resource.d3pie + '/d3pie/d3pie.min.js')}"
                  afterScriptsLoaded="{!c.doInit}"/>
    
    <div class="slds-card__body">
        <div id="pieChart"></div>
    </div>
    
</aura:component>

Controller.js

({
    doInit: function (cmp, event, helper) {
        helper.load(cmp);
    },
  })

Helper.js

({
    load: function(cmp) {
        var action = cmp.get("c.getLimits");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS"){
                var limits = response.getReturnValue();
                var arr = [];
                limits.forEach((key, value) => {
                    arr.push({
                    "label": limits[value].groupName,
                    "value": limits[value].usedPercentage
                });
            });
            console.log(arr);
            var pie = new d3pie("pieChart", {
                "header": {
                    "title": {
                        "text": "Salesforce Limits Pie Chart",
                        "fontSize": 34,
                        "font": "courier"
                    },
                    "location": "pie-center",
                    "titleSubtitlePadding": 10
                },
                "size": {
                    "canvasWidth": 790,
                    "pieInnerRadius": "95%",
                    "pieOuterRadius": "70%"
                },
                "data": {
                    "sortOrder": "label-desc",
                    "content": arr
                },
                "labels": {
                    "outer": {
                        "format": "label-percentage1",
                        "pieDistance": 20
                    },
                    "inner": {
                        "format": "none"
                    },
                    "mainLabel": {
                        "fontSize": 11
                    },
                    "percentage": {
                        "color": "#999999",
                        "fontSize": 11,
                        "decimalPlaces": 0
                    },
                    "value": {
                        "color": "#cccc43",
                        "fontSize": 11
                    },
                    "lines": {
                        "enabled": true,
                        "color": "#777777"
                    },
                    "truncation": {
                        "enabled": true
                    }
                },
                "effects": {
                    "pullOutSegmentOnClick": {
                        "effect": "linear",
                        "speed": 400,
                        "size": 8
                    }
                },
                "misc": {
                    "colors": {
                        "segmentStroke": "#000000"
                    }
                }
            });
            
        } else if(state == "ERROR"){
            var errors = response.getError();
            console.log(errors);
        }
        
    });
    $A.enqueueAction(action);
},
 
 })

 

Finally, the component output pie chart looks as shown below.