yaws icon indicating copy to clipboard operation
yaws copied to clipboard

Return single element array with JSON-RPC is impossible?

Open cl0ne opened this issue 3 years ago • 3 comments

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?

cl0ne avatar Apr 09 '21 13:04 cl0ne

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.

vinoski avatar Apr 09 '21 14:04 vinoski

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.

cl0ne avatar Apr 09 '21 14:04 cl0ne

Right, the backward compatibility issue is the problem with changing this.

vinoski avatar Apr 12 '21 12:04 vinoski