added promise support for RPC macro

This commit is contained in:
Djeeberjr 2023-08-10 21:52:02 +02:00
parent ad0c62d6e5
commit e593fc52c4
2 changed files with 40 additions and 5 deletions

View File

@ -1,6 +1,6 @@
package macros;
#if macro
import haxe.macro.ComplexTypeTools;
import haxe.macro.TypeTools;
import haxe.macro.Expr.Position;
import haxe.macro.Expr.ComplexType;
@ -39,5 +39,22 @@ class Helper {
return false;
}
}
public static function isPromise(t:Type):Bool {
return switch (t) {
case TType(t, params):
t.toString() == "tink.Promise";
default:
false;
}
}
public static function getPromiseType(t:ComplexType):Type {
switch (ComplexTypeTools.toType(t)) {
case TType(t, params):
return params[0];
case _:
return null;
}
}
}
#end

View File

@ -1,5 +1,7 @@
package macros.rpc;
import haxe.macro.ComplexTypeTools;
import haxe.macro.TypeTools;
import haxe.macro.Context;
import haxe.macro.Expr;
@ -10,7 +12,6 @@ class RPC {
var fields = Context.getBuildFields();
var className = Context.getLocalClass().get().name + "RPC";
var imports = Context.getLocalImports();
var c = macro class $className extends macros.rpc.RPCBase {
public function new(id:kernel.net.Package.NetworkID) {
@ -29,12 +30,17 @@ class RPC {
var argsExprs:Array<Expr> = [for (a in f.args) macro $i{a.name}];
var convertedArgs = [];
for (a in f.args) {
a.type = Helper.resolveType(a.type, field.pos);
convertedArgs.push(a);
}
var rtn = if (Helper.isPromise(ComplexTypeTools.toType(f.ret))) {
TypeTools.toComplexType(Helper.getPromiseType(f.ret));
} else {
Helper.resolveType(f.ret, field.pos);
}
c.fields.push({
name: field.name,
pos: field.pos,
@ -43,7 +49,7 @@ class RPC {
expr: macro {
return cast this._performRequest($v{field.name}, $a{argsExprs});
},
ret: Helper.newPromise(Helper.resolveType(f.ret, field.pos)),
ret: Helper.newPromise(rtn),
}),
access: [APublic],
doc: null,
@ -59,6 +65,10 @@ class RPC {
}
macro static public function generateRPCPackageHandle() {
#if display
return macro {};
#end
var proto = Context.getLocalClass().get().name + "RPC";
var exprs:Array<Expr> = [];
@ -87,6 +97,14 @@ class RPC {
pack.respond(null);
}
});
} else if (Helper.isPromise(ret)) {
exprs.push(macro {
if (pack.data.func == $v{funName}) {
this.$funName($a{callArgs}).handle((r) -> {
pack.respond(r);
});
}
});
} else {
exprs.push(macro {
if (pack.data.func == $v{funName}) {