Monday, March 30, 2020

Component to fetch and display Country-wise COVID19 Data in Lightning Web Component


                 Note: The Data is being fetched from the public API (Click here for reference). 




Components:

Covid19Data - Apex class for making callouts.
covid19LWC - Lightning Web Component for displaying the data from the callout.
Endpoint_Covid19 - Remote Site Settings to enable our Salesforce org to make callouts to the desired endpoint.
COVID 19 Data - Lightning Tab to accommodate covid19LWC.


-------------------- Covid19Data.apxc -----------------------

public class Covid19Data {

    @AuraEnabled(cacheable=true)
    public static List<wrapperData> getCovid19SummaryData(){
        
        List<wrapperData> returnVal = new List<wrapperData>();
        
        http h = new http();
        httprequest req = new httprequest();
        req.setEndpoint('https://api.covid19api.com/summary');
        req.setHeader('Accept', 'application/json');
        req.setMethod('GET');
        req.setTimeout(12000);
        
        httpresponse res = h.send(req);
        
        if (res.getStatusCode() == 200) {
            Map<String, Object> responseResult = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            List<Object> objects = (List<Object>) responseResult.get('Countries');
            for(Object obj : objects){
                wrapperData wrapperObj = new wrapperData();
                String strResult = JSON.serialize(obj);
                wrapperObj = (wrapperData) JSON.deserialize(strResult, wrapperData.class);
                if(String.isNotBlank(wrapperObj.Country)) returnVal.add(wrapperObj);
            }
        }
        return returnVal;
    }
    
    public class wrapperData{
        @AuraEnabled
        public string Country;
        @AuraEnabled
        public integer NewConfirmed;
        @AuraEnabled
        public integer TotalConfirmed;
        @AuraEnabled
        public integer NewDeaths;
        @AuraEnabled
        public integer TotalDeaths;
        @AuraEnabled
        public integer NewRecovered;
        @AuraEnabled
        public integer TotalRecovered;
    }
}