Skip to content

Commit

Permalink
- Renamed to Q
Browse files Browse the repository at this point in the history
- Made Error Handler Return Object
  • Loading branch information
ChuckJonas committed Oct 18, 2016
1 parent 9a8dcb9 commit 5640672
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 79 deletions.
87 changes: 57 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
# apex-promises
# APEX-Q

A promise library for Salesforce.

## Why?!
This was inspired by a 2016 Dreamforce Sessions [Apex Promises](https://success.salesforce.com/Sessions?eventId=a1Q3000000qQOd9EAG#/session/a2q3A000000LBdnQAG) by [Kevin Poorman](https://github.com/codefriar). I thought it would be fun to take it a step further and see how close you could get to a reusable "Promise" implementation.

## Usage:
This was inspired by a 2016 Dreamforce Sessions [Apex Promises](https://success.salesforce.com/Sessions?eventId=a1Q3000000qQOd9EAG#/session/a2q3A000000LBdnQAG) by [Kevin Poorman](https://github.com/codefriar). I thought it would be fun to take it a step further and see how close you could get to a reusable "Promise" implementation.

## Usage

### Notes

* The return object of each `Resolve` function is passed into the next
* If an Exception is thown, the Exception Handler will be called
* The Done handler will be called at the very end, even if an error is thown

### Without Callouts
For Promises without Callouts, Inner-Classes and Non-Serializable types can be used. The Promise Library will chain these without using the future method. Below is a trivial example Encypts and Base64 encodes an Account Number field:

For Q's without Callouts, Inner-Classes and Non-Serializable types can be used. The Q Library will chain these without using the future method. Below is a trivial example Encypts and Base64 encodes an Account Number field:

``` java
public class EncryptionPromise{
public class EnycriptAccountNumber{

public EncryptionPromise(Account acc){
public EnycriptAccountNumber(Account acc){
Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);

new Promise(new EncryptionAction(exampleIv, key))
new Q(new EncryptionAction(exampleIv, key))
.then(new Base64EncodingAction())
.then(new ExceptionAction(false)) //set to true to see error handling
.error(new ErrorHandler(acc))
.done(new DoneHandler(acc))
.execute(Blob.valueOf(acc.AccountNumber));
}

//=== ACTION Handlers ===
private class EncryptionAction implements Promise.Action{
private class EncryptionAction implements Q.Action{
private Blob vector;
private Blob key;
public EncryptionAction(Blob vector, Blob key){
Expand All @@ -37,16 +48,29 @@ public class EncryptionPromise{
}
}

private class Base64EncodingAction implements Promise.Action {
private class Base64EncodingAction implements Q.Action {
public Object resolve(Object input){
Blob inputBlob = (Blob) input;
return EncodingUtil.base64Encode(inputBlob);
}
}

private class ExceptionAction implements Q.Action {
private Boolean throwException;
public ExceptionAction(Boolean throwException){
this.throwException = throwException;
}
public Object resolve(Object input){
if(throwException){
System.debug(100/0);
}
return input;
}
}


//=== Done Handler ===
private class DoneHandler implements Promise.Done{
private class DoneHandler implements Q.Done{
private Account acc;
public DoneHandler(Account acc){
this.acc = acc;
Expand All @@ -55,76 +79,79 @@ public class EncryptionPromise{
public void done(Object input){
if(input != null){
acc.AccountNumber = (String) input;
System.debug(input);
update acc;
insert acc;
System.debug(acc);
}
}
}

//=== DONE Handler ===
private class ErrorHandler implements Promise.Error{
//=== Error Handler ===
private class ErrorHandler implements Q.Error{
private Account acc;
public ErrorHandler(Account acc){
this.acc = acc;
}

//failed! set account number to null
public void error(Exception e){
public Object error(Exception e){
//do stuff with exception
System.debug(e.getMessage());

//return object for done
acc.AccountNumber = null;
System.debug(e);
update acc;
return acc;
}
}
}
```

**Note:**
* The return object of each Resolve function is passed into the next
* The Done handler will be called even if there is an error

### With Callouts

The most common use case for a pattern like this would probably be to chain multiple Callout actions. Unforuntely, due to the lack of proper reflection in Salesforce, the implementation here is less than ideal and rules must be followed:

1. All interfaced Promise implementations (Action, Error, Done) MUST be Top Level classes. Using Inner Classes will cause failures.
2. All implemented classes MUST be JSON serializable. Non-Serailizable types will cause a failure!
3. Resolve MUST return a `CalloutPromise.TypedSerializable`
3. Resolve MUST return a `QFuture.TypedSerializable`

To Specify a Promise with callouts, just use `CalloutPromise` in place of `Promise`:
To Specify a Promise with callouts, just use `QFuture` in place of `Q`:

``` java
public class EncryptionPromise{
public class EnycriptAccountNumber{

//ALL Promise Implementation Classes defined at top level!
public EncryptionPromise(Account acc){
Blob exampleIv = Blob.valueOf('abc');
public EnycriptAccountNumber(Account acc){
Blob exampleIv = Blob.valueOf('Example of IV123');
Blob key = Crypto.generateAesKey(128);

new CalloutPromise(new EncryptionAction(exampleIv, key))
new QFuture(new EncryptionAction(exampleIv, key))
.then(new Base64EncodingAction())
.then(new ExceptionAction(false)) //set to true to see error handling
.error(new ErrorHandler(acc))
.done(new DoneHandler(acc))
.execute(Blob.valueOf(acc.AccountNumber));
}
}

public with sharing class EncryptionAction implements Promise.Action{
public with sharing class EncryptionAction implements Q.Action{
private Blob vector;
private Blob key;
public EncryptionAction(Blob vector, Blob key){
this.vector = vector;
this.key = key;
}

public CalloutPromise.TypedSerializable resolve(Object input){
public QFuture.TypedSerializable resolve(Object input){
Blob inputBlob = (Blob) input;
return new CalloutPromise.TypedSerializable(Crypto.encrypt('AES128', key, vector, inputBlob),
return new QFuture.TypedSerializable(Crypto.encrypt('AES128', key, vector, inputBlob),
Blob.class);
}
}
```

## Disclaimer
I have not (and maybe would not) use this in an actual implementation. Has not been throughly tested.
***IMPLEMENT AT YOUR OWN RISK.***
I have not use this in an actual implementation. Has not been throughly tested. Needs Unit Testing

## LICENSE
The MIT License (MIT)
Expand Down
30 changes: 15 additions & 15 deletions src/classes/Promise.cls → src/classes/Q.cls
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
//Author: Charlie Jonas
// Proof of concept for a 'Promise-Like' implementation using Apex Queueables.
public virtual class Promise extends BasePromise implements Queueable {
// Runs a "Syncronous" (not really, still runs in multiple batches) Q process
public virtual class Q extends QBase implements Queueable {

//store promise actions to execute.
// If we implement 'Database.AllowCallouts' then use the StackItem to serialize the stack.
//store promise actions to execute.
// If we implement 'Database.AllowCallouts' then use the StackItem to serialize the stack.
// Otherwise just store Promise Actions
protected List<Action> promiseStack = new List<Action>();

public Promise(){}

public Promise(Action action){
public Q(){}

public Q (Action action){
then(action);
}

//=== Methods ===

/**
* Add a new promise action to the execution stack
* @param action Action to execute
* @return this (for chaining)
*/
public override BasePromise then(Action action){
public override QBase then(Action action){
promiseStack.add(action);
return this;
}
Expand All @@ -34,26 +34,26 @@ public virtual class Promise extends BasePromise implements Queueable {
Action currentPromise;
Object resolution;
try{

currentPromise = promiseStack.remove(0);
heap = currentPromise.resolve(heap);

//continue execution
if(promiseStack.size() > 0){
System.enqueueJob(this);
return;
return;
}
}catch(Exception e){
if(errorHandler != null){
errorHandler.error(e);
heap = errorHandler.error(e);
}else{
System.debug(e.getMessage());
System.debug(e.getStackTraceString());
throw e;
}
}

//All actions done, or error.
//All actions done, or error.
//Execute 'finally' method
if(doneHandler != null){
doneHandler.done(heap);
Expand All @@ -62,14 +62,14 @@ public virtual class Promise extends BasePromise implements Queueable {

//=== Interfaces ===
public interface Action {
//Execution action. Return "Response" object if successful.
//Execution action. Return "Response" object if successful.
//Otherwise throw exection
Object resolve(Object input);
}

//use as catch blocks
public interface Error {
void error(Exception e);
Object error(Exception e);
}

//use as finally blocks
Expand Down
File renamed without changes.
16 changes: 9 additions & 7 deletions src/classes/BasePromise.cls → src/classes/QBase.cls
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
public abstract class BasePromise {
//Author: Charlie Jonas
// Base Class for Apex "Q"
public abstract class QBase {

//handlers
public Promise.Error errorHandler;
public Promise.Done doneHandler;
protected Q.Error errorHandler;
protected Q.Done doneHandler;

//stores data to pass from one promise to the next
public Object heap;
public Object heap;

public abstract BasePromise then(Promise.Action action);
public abstract QBase then(Q.Action action);

/**
* Sets the error (Catch) handler. Can only have 1
* @param errorHandler The handler to use
* @return this (for chaining)
*/
public BasePromise error(Promise.Error errorHandler){
public QBase error(Q.Error errorHandler){
this.errorHandler = errorHandler;
return this;
}
Expand All @@ -24,7 +26,7 @@ public abstract class BasePromise {
* @param doneHandler The handler to use
* @return this (for chaining)
*/
public BasePromise done(Promise.Done doneHandler){
public QBase done(Q.Done doneHandler){
this.doneHandler = doneHandler;
return this;
}
Expand Down
File renamed without changes.
Loading

0 comments on commit 5640672

Please sign in to comment.