Apex Class QuandlApiService
public class QuandlApiService {
@AuraEnabled(cacheable=true)
public static String fetchNifty50Data() {
try {
// Fetch custom metadata for API configuration
API_Configuration__mdt config = [SELECT API_Endpoint__c, API_Key__c FROM API_Configuration__mdt WHERE DeveloperName = 'Quandl_Nifty50' LIMIT 1];
// Create an HTTP request
HttpRequest req = new HttpRequest();
Http http = new Http();
// Set the endpoint URL with the API key from metadata
String url = config.API_Endpoint__c + '?api_key=' + config.API_Key__c;
req.setEndpoint(url);
req.setMethod('GET');
// Send the request and get the response
HttpResponse res = http.send(req);
// Check the status code for success
if (res.getStatusCode() == 200) {
// Parse the JSON response
Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
Map<String, Object> dataset = (Map<String, Object>) responseMap.get('dataset');
// Debug the response structure
System.debug('Full Response: ' + responseMap);
// Get the list of column names
List<Object> columnNames = (List<Object>) dataset.get('column_names');
// Get the actual data
Object rawData = dataset.get('data');
// Debug the raw data
System.debug('Raw Data: ' + rawData);
// Initialize the result
String result = 'Nifty50 Data:\n';
// Handle different data structures
if (rawData instanceof List<List<Object>>) {
// Handle List of Lists
List<List<Object>> data = (List<List<Object>>) rawData;
for (List<Object> row : data) {
for (Integer i = 0; i < columnNames.size(); i++) {
result += (String) columnNames[i] + ': ' + String.valueOf(row[i]) + ', ';
}
result += '\n';
}
} else if (rawData instanceof List<Object>) {
// Handle Flat List
List<Object> data = (List<Object>) rawData;
for (Integer i = 0; i < columnNames.size(); i++) {
result += (String) columnNames[i] + ': ' + String.valueOf(data[i]) + '\n';
}
} else {
result += 'Unexpected data format';
}
return result;
} else {
return 'Failed to fetch data. Status code: ' + res.getStatusCode();
}
} catch (Exception e) {
System.debug('Error occurred: ' + e.getMessage());
return 'Error occurred: ' + e.getMessage();
}
}
}
Nifty50Card Js Code
import { LightningElement,wire,track } from 'lwc';
import fetchNifty50Data from '@salesforce/apex/QuandlApiService.fetchNifty50Data';
export default class Nifty50Data extends LightningElement {
@track data;
@track error;
@wire(fetchNifty50Data)
wiredNifty50Data({ error, data }) {
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.data = undefined;
this.error = error.body.message;
}
}
}
Nifty50Card Html Code
<template>
<lightning-card title="Nifty50 Data">
<template if:true={data}>
<pre>{data}</pre>
</template>
<template if:true={error}>
<p class="slds-text-color_error">{error}</p>
</template>
</lightning-card>
</template>
Please Click Link Output Result
No comments:
Post a Comment