Created
June 8, 2020 01:57
-
-
Save visaolive/53b4b8a3c8c2c7445d92f136b2de134e to your computer and use it in GitHub Desktop.
GoogleOrderPubSubQueueable.cls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GoogleOrderPubSubQueueable implements Queueable, Database.AllowsCallouts { | |
public List<Order> orderList; | |
public GoogleOrderPubSubQueueable(List<Order> order){ | |
this.orderList=order; | |
} | |
public void execute(QueueableContext context) { | |
//GCP Authentication | |
GCPAuthManagementService gms = new GCPAuthManagementService(); | |
GCP_Key__mdt serviceAccount = gms.getGCPServiceAccount('Salesforce_PubSub_Orders'); | |
GCPAuthManagementService.GoogleAuthResponse gmsg = new GCPAuthManagementService.GoogleAuthResponse(); | |
gmsg = gms.getGCPAuthToken(serviceAccount); | |
String selectFields = serviceAccount.query_fields__c; | |
List<String> fields = selectFields.split(','); | |
String sobType = serviceAccount.object__c; | |
JSONGenerator gen = JSON.createGenerator(true); | |
gen.writeStartObject(); | |
gen.writeFieldName('records'); | |
gen.writeStartArray(); | |
for (SObject sob : Database.query('' | |
+ ' select ' + String.join(fields, ',') | |
+ ' from ' + sobType | |
+ ' where id IN: orderList' | |
)) { | |
gen.writeStartObject(); | |
for (String field : fields) { | |
Object value = sob.get(field); | |
// if no value returned, exclude from JSON | |
if (value != null) gen.writeStringField(field, String.valueOf(value)); | |
} | |
gen.writeEndObject(); | |
} | |
gen.writeEndArray(); | |
gen.writeEndObject(); | |
String body = gen.getAsString(); | |
System.debug('body-' + body); | |
// send order to google pubsub as message | |
HttpRequest req = new HttpRequest(); | |
req.setEndpoint(serviceAccount.audience__c); | |
req.setHeader('Content-Type', 'application/json'); | |
req.setHeader('Authorization', 'Bearer ' + gmsg.id_token); | |
req.setMethod('POST'); | |
req.setbody(body); | |
Http http = new Http(); | |
HTTPResponse response = http.send(req); | |
system.debug('HTTP Request: ' + req); | |
system.debug('HTTP Response: ' + response.getBody()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment