yaws
yaws copied to clipboard
Return single element array with JSON-RPC is impossible?
When we have a method that returns list of structs, depending on the element count we will get completely different results:
- list with 2+ structs will give an expected array with 2+ objects;
- empty list will give an empty string (okay, I get it, we have no way differentiate empty list from empty strings);
- list with single struct will be stripped down to object instead of an array with single object (of course, we can work around this by wrapping result list with a single-field object, but that looks like an ugly hack).
The question is why encode_handler_payload unwraps single-element lists?
This was apparently done in the very first version of the yaws_rpc
module; see 1791e3dc. My understanding is that the module was originally written to support Haxe, so perhaps it had/has a case that requires this.
I guess that replacing https://github.com/erlyaws/yaws/blob/ca704a916ee05113564668cf5281700db25021f3/src/yaws_rpc.erl#L393-L402
with
encode_handler_payload({response, ErlStruct}, ID, json) ->
StructStr = json2:encode({struct, [
{result, ErlStruct},
{id, ID},
{"jsonrpc", "2.0"}
]}),
{ok, StructStr};
encode_handler_payload({response, [ErlStruct]}, ID, haxe) ->
encode_handler_payload({response, ErlStruct}, ID, haxe);
encode_handler_payload({response, ErlStruct}, ID, haxe) ->
StructStr = [$h, $x, $r | haxe:encode(ErlStruct)],
{ok, StructStr}.
will fix the issue but breaks backward compatibility at the same time.
Right, the backward compatibility issue is the problem with changing this.