I have PostgreSQL sitting on Heroku and I will have to pull the data from Heroku into apex and display the data on VF page. Anybody can guide me how/where should I start from?
-
You can use the lightning connect / Heroku connect to get the data from the postgres db on heorku. Once the connection is established then the getting the data is as simple as writing an SOQl query.– SamCommented Apr 28, 2016 at 3:06
-
yes i know that once the connection is established it will be simple but my question how do i connect?– NickCommented Apr 28, 2016 at 3:17
1 Answer
Use the Heroku Connect API:
- Create a Heroku app and Heroku PostgreSQL database
- Create the Heroku Connect add-on
- Link the new add-on to your Heroku user account
- Retrieve the new connection's ID
- Configure the database key and schema for the connection
- Authenticate the connection to your Salesforce Org
- Import a mapping configuration
- Monitor the connection and mapping status
Then write the Apex code:
With the REST endpoint on Heroku ready to be consumed, it's now just a matter of writing some Apex code to bridge between Salesforce Connect and the service. For the example real estate REST service, we could have a simple Apex adapter that extends the DataSource.Connection class and implements the sync(), query(), and search() methods with a basic structure like:
global class RealEstateConnection extends DataSource.Connection { override global List search(DataSource.SearchContext searchContext) { } override global List sync() { } override global DataSource.TableResult query(DataSource.QueryContext queryContext) { } }
or create a trigger bound to an Apex callout:
The trigger can use an Apex callout to make a REST JSON call to an endpoint on a Heroku app. For instance, here is an Apex trigger that calls a Heroku app:
trigger NewContactWebhookTrigger on Contact (after insert) { String url = 'https://foo.herokuapp.com/new_contact'; String content = Webhook.jsonContent(Trigger.new, Trigger.old); Webhook.callout(url, content); }
The referenced Webhook Apex class is:
public class Webhook { public static String jsonContent(List triggerNew, List triggerOld) { String newObjects = '[]'; if (triggerNew != null) { newObjects = JSON.serialize(triggerNew); } String oldObjects = '[]'; if (triggerOld != null) { oldObjects = JSON.serialize(triggerOld); } String userId = JSON.serialize(UserInfo.getUserId()); String content = '{"new": ' + newObjects + ', "old": ' + oldObjects + ', "userId": ' + userId + '}'; return content; } @future(callout=true) public static void callout(String url, String content) { Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(url); req.setMethod('POST'); req.setHeader('Content-Type', 'application/json'); req.setBody(content); h.send(req); } }
References