Last active
January 7, 2021 06:05
-
-
Save douglascayers/fc8b704f2558d37dc47a to your computer and use it in GitHub Desktop.
Salesforce apex class that exposes the BitlyService via @InvocableMethod to be called by Process Builder. The .java extension is just for syntax highlighting, save them as .cls in your project.
This file contains 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 BitlyShortenURLInvocable { | |
@InvocableMethod( | |
label = 'shorten' | |
description = 'Given case IDs then generates a bitly short url for them' | |
) | |
public static void shorten(List<ID> caseIds) { | |
// You can't invoke http callouts from Process Builder or Flow | |
// because the database transaction has not committed yet, you will get error: | |
// "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out" | |
// To get around this then we'll actually make the call in a @Future method asynchronously. | |
shortenAsync( caseIds ); | |
} | |
@Future(callout = true) | |
private static void shortenAsync(List<ID> caseIds) { | |
// Fetch your data and a field where you want to store the generated short url | |
List<Case> cases = new List<Case>([ SELECT Id, Short_URL__c FROM Case WHERE Id IN :caseIds ]); | |
// Service to actually call out to bitly and get a shortened url | |
BitlyService service = new BitlyService(); | |
// Bitly does not support bulk url shortening | |
// so you must make each call individually. | |
// Do be aware of Bitly's rate limiting if you try | |
// to mass create a bunch of records in short succession | |
// https://dev.bitly.com/docs/getting-started/rate-limits | |
for ( Case caseObj : cases ) { | |
// in this trivial example, we're just creating short urls to the record itself | |
caseObj.Short_URL__c = service.shorten( 'https://login.salesforce.com/' + caseObj.id ); | |
} | |
// update the records with their short urls | |
// use workflow or trigger to fire off the short url field being populated | |
// to then send email alerts, etc. including the short url | |
if ( cases.size() > 0 ) { | |
update cases; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The BitlyService I blogged about here: https://douglascayers.wordpress.com/2015/10/21/salesforce-create-short-urls-with-bitly-process-builder-and-apex/
Gist to the apex tests are here: https://gist.github.com/DouglasCAyers/de978590b97e235a96fc