Skip to content

Commit

Permalink
Add promise serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Brain committed Aug 18, 2017
1 parent 8975b6d commit b7a6f53
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/conf/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export let CONSTANTS = {

SERIALIZATION_TYPES: {
METHOD: 'postrobot_method',
ERROR: 'postrobot_error'
ERROR: 'postrobot_error',
PROMISE: 'postrobot_promise'
},

SEND_STRATEGIES: {
Expand Down
27 changes: 26 additions & 1 deletion src/lib/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,18 @@ function serializeError(err : mixed) : SerializedError {
};
}

type SerializePromise = {
__type__ : string,
__then__ : SerializedMethod
};

function serializePromise(destination : any, domain : string, promise : ZalgoPromise<mixed>, name : string) : SerializePromise {
return {
__type__: CONSTANTS.SERIALIZATION_TYPES.PROMISE,
__then__: serializeMethod(destination, domain, (resolve, reject) => promise.then(resolve, reject), `${name}.then`)
};
}

export function serializeMethods(destination : any, domain : string, obj : Object) : Object {

return replaceObject({ obj }, (item, key) => {
Expand All @@ -99,10 +111,15 @@ export function serializeMethods(destination : any, domain : string, obj : Objec
if (item instanceof Error) {
return serializeError(item);
}

if (ZalgoPromise.isPromise(item)) {
// $FlowFixMe
return serializePromise(destination, domain, item, key.toString());
}
}).obj;
}

export function deserializeMethod(source : any, origin : string, obj : Object) : Object {
export function deserializeMethod(source : any, origin : string, obj : Object) : Function {

function wrapper() : ZalgoPromise<mixed> {
let args = Array.prototype.slice.call(arguments);
Expand Down Expand Up @@ -135,6 +152,10 @@ export function deserializeError(source : any, origin : string, obj : Object) :
return new Error(obj.__message__);
}

export function deserializePromise(source : any, origin : string, prom : Object) : ZalgoPromise<mixed> {
return new ZalgoPromise((resolve, reject) => deserializeMethod(source, origin, prom.__then__)(resolve, reject));
}

export function deserializeMethods(source : any, origin : string, obj : Object) : Object {

return replaceObject({ obj }, (item, key) => {
Expand All @@ -147,5 +168,9 @@ export function deserializeMethods(source : any, origin : string, obj : Object)
return deserializeError(source, origin, item);
}

if (typeof item === 'object' && item !== null && isSerialized(item, CONSTANTS.SERIALIZATION_TYPES.PROMISE)) {
return deserializePromise(source, origin, item);
}

}).obj;
}

0 comments on commit b7a6f53

Please # to comment.