├── .gitignore
├── src
├── classes
│ ├── Q.cls-meta.xml
│ ├── QBase.cls-meta.xml
│ ├── QFuture.cls-meta.xml
│ ├── QBase.cls
│ ├── Q.cls
│ └── QFuture.cls
└── package.xml
├── package.json
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
--------------------------------------------------------------------------------
/src/classes/Q.cls-meta.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 35.0
4 | Active
5 |
6 |
--------------------------------------------------------------------------------
/src/classes/QBase.cls-meta.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 35.0
4 | Active
5 |
6 |
--------------------------------------------------------------------------------
/src/classes/QFuture.cls-meta.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 35.0
4 | Active
5 |
6 |
--------------------------------------------------------------------------------
/src/package.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | *
5 | ApexClass
6 |
7 | 35.0
8 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "apex-promises",
3 | "version": "1.0.0",
4 | "description": "A Salesforce Promise library",
5 | "main": "index.js",
6 | "scripts": {
7 | "postinstall": "node -e \"require('sfdc-pkg-postinstall').install()\"",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "git+https://github.com/ChuckJonas/apex-promises.git"
13 | },
14 | "keywords": [
15 | "sfdc-package"
16 | ],
17 | "author": "Charles Jonas",
18 | "license": "MIT",
19 | "bugs": {
20 | "url": "https://github.com/ChuckJonas/apex-promises/issues"
21 | },
22 | "homepage": "https://github.com/ChuckJonas/apex-promises#readme",
23 | "dependencies": {
24 | "sfdc-pkg-postinstall": "^1.0.0"
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/classes/QBase.cls:
--------------------------------------------------------------------------------
1 | //Author: Charlie Jonas
2 | // Base Class for Apex "Q"
3 | public abstract class QBase {
4 |
5 | //handlers
6 | protected Q.Error errorHandler;
7 | protected Q.Done doneHandler;
8 |
9 | //stores data to pass from one promise to the next
10 | public Object heap;
11 |
12 | public abstract QBase then(Q.Action action);
13 |
14 | /**
15 | * Sets the error (Catch) handler. Can only have 1
16 | * @param errorHandler The handler to use
17 | * @return this (for chaining)
18 | */
19 | public QBase error(Q.Error errorHandler){
20 | this.errorHandler = errorHandler;
21 | return this;
22 | }
23 |
24 | /**
25 | * Sets the Done (Finally) handler. Can only have 1
26 | * @param doneHandler The handler to use
27 | * @return this (for chaining)
28 | */
29 | public QBase done(Q.Done doneHandler){
30 | this.doneHandler = doneHandler;
31 | return this;
32 | }
33 |
34 | /**
35 | * starts the promise execution
36 | * @param input Object to pass to the first Action
37 | */
38 | public void execute(Object input){
39 | heap = input;
40 | System.enqueueJob(this);
41 | }
42 | }
--------------------------------------------------------------------------------
/src/classes/Q.cls:
--------------------------------------------------------------------------------
1 | //Author: Charlie Jonas
2 | // Runs a "Syncronous" (not really, still runs in multiple batches) Q process
3 | public virtual class Q extends QBase implements Queueable {
4 |
5 | //store promise actions to execute.
6 | // If we implement 'Database.AllowCallouts' then use the StackItem to serialize the stack.
7 | // Otherwise just store Promise Actions
8 | protected List promiseStack = new List();
9 |
10 | public Q(){}
11 |
12 | public Q (Action action){
13 | then(action);
14 | }
15 |
16 | //=== Methods ===
17 |
18 | /**
19 | * Add a new promise action to the execution stack
20 | * @param action Action to execute
21 | * @return this (for chaining)
22 | */
23 | public override QBase then(Action action){
24 | promiseStack.add(action);
25 | return this;
26 | }
27 |
28 | /**
29 | * Runs through the promises execution stack, chaining a new Queuable for each Action
30 | * @param context System Injected
31 | */
32 | public void execute(QueueableContext context) {
33 |
34 | Action currentPromise;
35 | Object resolution;
36 | try{
37 |
38 | currentPromise = promiseStack.remove(0);
39 | heap = currentPromise.resolve(heap);
40 |
41 | //continue execution
42 | if(promiseStack.size() > 0){
43 | System.enqueueJob(this);
44 | return;
45 | }
46 | }catch(Exception e){
47 | if(errorHandler != null){
48 | heap = errorHandler.error(e);
49 | }else{
50 | System.debug(e.getMessage());
51 | System.debug(e.getStackTraceString());
52 | throw e;
53 | }
54 | }
55 |
56 | //All actions done, or error.
57 | //Execute 'finally' method
58 | if(doneHandler != null){
59 | doneHandler.done(heap);
60 | }
61 | }
62 |
63 | //=== Interfaces ===
64 | public interface Action {
65 | //Execution action. Return "Response" object if successful.
66 | //Otherwise throw exection
67 | Object resolve(Object input);
68 | }
69 |
70 | //use as catch blocks
71 | public interface Error {
72 | Object error(Exception e);
73 | }
74 |
75 | //use as finally blocks
76 | public interface Done{
77 | void done(Object input);
78 | }
79 |
80 | }
--------------------------------------------------------------------------------
/src/classes/QFuture.cls:
--------------------------------------------------------------------------------
1 | //Author: Charlie Jonas
2 | //Use for promises that require callouts. Will attempt to serialize data.
3 | // IMPORTANT: Due to Apex's lack of proper reflection,
4 | // All Action, Error & Done classes MUST be Top level and completely serializable!
5 | // Inner classes and non-serializable properties will cause failure!
6 | public class QFuture extends QBase implements Queueable, Database.AllowsCallouts {
7 | //store promise actions to execute.
8 | protected List promiseStack = new List();
9 |
10 | public QFuture(){}
11 |
12 | public QFuture(Q.Action action){
13 | then(action);
14 | }
15 |
16 | /**
17 | * Add a new promise action to the execution stack
18 | * @param action Action to execute
19 | * @return this (for chaining)
20 | */
21 | public override QBase then(Q.Action action){
22 | promiseStack.add(new TypedSerializable(action));
23 | return this;
24 | }
25 |
26 | /**
27 | * Runs through the promises execution stack, chaining a new Queuable for each Action
28 | * @param context System Injected
29 | */
30 | public void execute(QueueableContext context) {
31 |
32 | Q.Action currentPromise;
33 | TypedSerializable resolution;
34 | try{
35 | TypedSerializable si = (TypedSerializable) promiseStack.remove(0);
36 | currentPromise = (Q.Action) JSON.deserialize(si.objJSON, Type.forName(si.classType));
37 |
38 | resolution = (TypedSerializable) currentPromise.resolve(heap);
39 |
40 | //continue execution
41 | if(promiseStack.size() > 0){
42 | enqueueJobFuture(
43 | getInstanceClassName(this),
44 | JSON.serialize(promiseStack),
45 | resolution.objJSON,
46 | resolution.classType,
47 | errorHandler==null?null:JSON.serialize(errorHandler),
48 | getInstanceClassName(errorHandler),
49 | doneHandler==null?null:JSON.serialize(doneHandler),
50 | getInstanceClassName(doneHandler)
51 | );
52 | return;
53 | }
54 | }catch(Exception e){
55 | if(errorHandler != null){
56 | resolution = (TypedSerializable) errorHandler.error(e);
57 | }else{
58 | System.debug(e.getMessage());
59 | System.debug(e.getStackTraceString());
60 | throw e;
61 | }
62 | }
63 |
64 | //All actions done, or error.
65 | //Execute 'finally' method
66 | if(doneHandler != null){
67 | doneHandler.done(JSON.deserialize(resolution.objJSON, Type.forName(resolution.classType)));
68 | }
69 | }
70 |
71 | /**
72 | * Method to enqueue for future execution. Used for Callout Promise,
73 | * or possibily other extension of promise that levelage callouts
74 | * @param promiseClassName The name of the Promise Class we are Executing
75 | * @param promiseStack Serialized list of StackItem
76 | * @param heap Seralized values to pass to next execution
77 | * @param heapClassName Heap Object Type
78 | * @param error Serialized error handler class
79 | * @param errorClassName Error Handler Class Type
80 | * @param done Serialized Done handler class
81 | * @param doneClassName Done Handler Class Type
82 | */
83 | @future(callout=true)
84 | public static void enqueueJobFuture(String promiseClassName, String promiseStack,
85 | String heap, String heapClassName,
86 | String error, String errorClassName,
87 | String done, String doneClassName){
88 |
89 | QFuture p = new QFuture();
90 | p.promiseStack = (List) JSON.deserialize(promiseStack, TypedSerializable[].class);
91 |
92 | if(error != null && errorClassName != null){
93 | p.error((Q.Error) JSON.deserialize(error, Type.forName(errorClassName)));
94 | }
95 |
96 | if(done != null && doneClassName != null){
97 | p.done((Q.Done) JSON.deserialize(done, Type.forName(doneClassName)));
98 | }
99 |
100 | if(heap != null && heapClassName != null){
101 | Type heapType = Type.forName(heapClassName);
102 | if(heapType == null){ //use generic class
103 | p.heap = JSON.deserializeUntyped(heap);
104 | }else{
105 | p.heap = JSON.deserialize(heap, heapType);
106 | }
107 | }
108 |
109 | //enqueue
110 | System.enqueueJob(p);
111 | }
112 |
113 | //=== Helpers ===
114 | private static String getInstanceClassName(Object o){
115 | if(o == null) return null;
116 | return String.valueOf(o).split(':')[0];
117 | }
118 |
119 | //=== Helper Classes ===
120 | public class TypedSerializable{
121 | public TypedSerializable(Q.Action action){
122 | classType = getInstanceClassName(action);
123 | objJSON = JSON.serialize(action);
124 | }
125 |
126 | public TypedSerializable(Object obj, Type t){
127 | this.objJSON = JSON.serialize(obj);
128 | this.classType = t.getName();
129 | }
130 |
131 | public String classType {get; private set;}
132 | public String objJSON {get; private set;}
133 | }
134 |
135 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # APEX-Q
2 |
3 | A promise library for Salesforce.
4 |
5 | ## Why?!
6 |
7 | 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.
8 |
9 | ## Usage
10 |
11 | ### Notes
12 |
13 | * The return object of each `Resolve` function is passed into the next
14 | * If an Exception is thown, the Exception Handler will be called
15 | * The Done handler will be called at the very end, even if an error is thown
16 |
17 | ### Without Callouts
18 |
19 | 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:
20 |
21 | ``` java
22 | public class EnycriptAccountNumber{
23 |
24 | public EnycriptAccountNumber(Account acc){
25 | Blob exampleIv = Blob.valueOf('Example of IV123');
26 | Blob key = Crypto.generateAesKey(128);
27 |
28 | new Q(new EncryptionAction(exampleIv, key))
29 | .then(new Base64EncodingAction())
30 | .then(new ExceptionAction(false)) //set to true to see error handling
31 | .error(new ErrorHandler(acc))
32 | .done(new DoneHandler(acc))
33 | .execute(Blob.valueOf(acc.AccountNumber));
34 | }
35 |
36 | //=== ACTION Handlers ===
37 | private class EncryptionAction implements Q.Action{
38 | private Blob vector;
39 | private Blob key;
40 | public EncryptionAction(Blob vector, Blob key){
41 | this.vector = vector;
42 | this.key = key;
43 | }
44 |
45 | public Object resolve(Object input){
46 | Blob inputBlob = (Blob) input;
47 | return Crypto.encrypt('AES128', key, vector, inputBlob);
48 | }
49 | }
50 |
51 | private class Base64EncodingAction implements Q.Action {
52 | public Object resolve(Object input){
53 | Blob inputBlob = (Blob) input;
54 | return EncodingUtil.base64Encode(inputBlob);
55 | }
56 | }
57 |
58 | private class ExceptionAction implements Q.Action {
59 | private Boolean throwException;
60 | public ExceptionAction(Boolean throwException){
61 | this.throwException = throwException;
62 | }
63 | public Object resolve(Object input){
64 | if(throwException){
65 | System.debug(100/0);
66 | }
67 | return input;
68 | }
69 | }
70 |
71 |
72 | //=== Done Handler ===
73 | private class DoneHandler implements Q.Done{
74 | private Account acc;
75 | public DoneHandler(Account acc){
76 | this.acc = acc;
77 | }
78 |
79 | public void done(Object input){
80 | if(input != null){
81 | acc.AccountNumber = (String) input;
82 | insert acc;
83 | System.debug(acc);
84 | }
85 | }
86 | }
87 |
88 | //=== Error Handler ===
89 | private class ErrorHandler implements Q.Error{
90 | private Account acc;
91 | public ErrorHandler(Account acc){
92 | this.acc = acc;
93 | }
94 |
95 | //failed! set account number to null
96 | public Object error(Exception e){
97 | //do stuff with exception
98 | System.debug(e.getMessage());
99 |
100 | //return object for done
101 | acc.AccountNumber = null;
102 | return acc;
103 | }
104 | }
105 | }
106 | ```
107 |
108 |
109 | ### With Callouts
110 |
111 | 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:
112 |
113 | 1. All interfaced Promise implementations (Action, Error, Done) MUST be Top Level classes. Using Inner Classes will cause failures.
114 |
115 | 2. All implemented classes MUST be JSON serializable. Non-Serailizable types will cause a failure!
116 |
117 | 3. Resolve MUST return a `QFuture.TypedSerializable`
118 |
119 | To Specify a Promise with callouts, just use `QFuture` in place of `Q`:
120 |
121 | ``` java
122 | public class EnycriptAccountNumber{
123 |
124 | //ALL Promise Implementation Classes defined at top level!
125 | public EnycriptAccountNumber(Account acc){
126 | Blob exampleIv = Blob.valueOf('Example of IV123');
127 | Blob key = Crypto.generateAesKey(128);
128 |
129 | new QFuture(new EncryptionAction(exampleIv, key))
130 | .then(new Base64EncodingAction())
131 | .then(new ExceptionAction(false)) //set to true to see error handling
132 | .error(new ErrorHandler(acc))
133 | .done(new DoneHandler(acc))
134 | .execute(Blob.valueOf(acc.AccountNumber));
135 | }
136 | }
137 | //TOP LEVEL CLASS!
138 | public with sharing class EncryptionAction implements Q.Action{
139 | private Blob vector;
140 | private Blob key;
141 | public EncryptionAction(Blob vector, Blob key){
142 | this.vector = vector;
143 | this.key = key;
144 | }
145 |
146 | public QFuture.TypedSerializable resolve(Object input){
147 | Blob inputBlob = (Blob) input;
148 | return new QFuture.TypedSerializable(Crypto.encrypt('AES128', key, vector, inputBlob),
149 | Blob.class);
150 | }
151 | }
152 | //... Rest of implementations. (Also top level)
153 | ```
154 |
155 | ## Installation
156 |
157 | 1. `cd [workspace` (should contain `src`)
158 |
159 | 2. `npm install apex-q` (this will also create a `node_modules` folder)
160 |
161 | 3. use your favorite IDE to deploy classes
162 |
163 | ## Disclaimer
164 | ***IMPLEMENT AT YOUR OWN RISK.***
165 | I have not use this in an actual implementation. Has not been throughly tested. Needs Unit Testing
166 |
167 | ## LICENSE
168 | The MIT License (MIT)
169 |
170 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
171 |
172 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
173 |
174 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
175 |
--------------------------------------------------------------------------------