Skip to content

Instantly share code, notes, and snippets.

@maujood
Last active March 10, 2021 05:21
Show Gist options
  • Save maujood/1caf92ac2507967964d3a8d2bcae413e to your computer and use it in GitHub Desktop.
Save maujood/1caf92ac2507967964d3a8d2bcae413e to your computer and use it in GitHub Desktop.
Utility Component to call Apex and SOQL from Lightning Components using just one line of code
<aura:component extensible="true"
controller="ApexHelperController">
{!v.body}
</aura:component>
public with sharing class ApexHelperController {
@AuraEnabled
public static List<sObject> executeSoql(String soql) {
List<sObject> result = Database.query(soql);
return result;
}
}
({
apex: function(cmp, method, params) {
return new Promise(function (resolve, reject) {
var action = cmp.get("c." + method);
action.setParams(params);
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
resolve(response.getReturnValue());
}
else if (state === "INCOMPLETE") {
// do something
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors && errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
reject(errors[0].message);
} else {
console.log("Unknown error");
reject("Unknown error");
}
}
});
$A.enqueueAction(action);
});
},
soql: function (cmp, query) {
return new Promise(function (resolve, reject) {
var action = cmp.get("c.executeSoql");
action.setParams({soql: query});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
resolve(response.getReturnValue());
}
else if (state === "INCOMPLETE") {
// do something
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors && errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
reject(errors[0].message);
} else {
console.log("Unknown error");
reject("Unknown error");
}
}
});
$A.enqueueAction(action);
});
}
})
@maujood
Copy link
Author

maujood commented Feb 4, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment