8000 Support for `oneof` attributes missing when using JSON? · Issue #156 · keathley/twirp-elixir · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Support for oneof attributes missing when using JSON? #156
Open
@zookzook

Description

@zookzook

Thank you for this package!

Assume the following protobuf definition:

 message Result {
  oneof result {
    Success success = 1;    
    Error error = 2;          
  }

  message Success {
    string processed_at = 1;  
  }

  message Error {
    int32  status = 1;        
    string title = 2;         
    string detail = 3;        
  }
}

The elixir struct looks this:

defmodule Result do
  @moduledoc false
  use Protobuf, syntax: :proto3

  @type t :: %__MODULE__{
          result:
            {:success, Result.Success.t() | nil}
            | {:error, Result.Error.t() | nil}
        }

  defstruct result: nil

  oneof :result, 0

  field :success, 1, type: Result.Success, oneof: 0
  field :error, 2, type: Result.Error, oneof: 0
end

If I create new Result:

    success = Result.Success.new(processed_at: processed_at)
    Result.new(result: {:success, success})

An error is returned from the RPC if I use JSON as output format:

protocol Jason.Encoder not implemented for {:success,....

But if I use the Protobuf.JSON.to_encodable/1 from :protobuf it correct (lowerCamelCase):

%{"success" => %{"processedAt" => ...}}

Solution: Instead of using Jason to convert the generated structs, the function Protobuf.JSON.to_encodable/1 should used to convert the struct in a previous step.

Of course, it is possible to use the Twirp.Error stuff, but this is only an example, that in case of oneof definition the Jason encoder should not called direct on the structs, because the oneof attribute uses tuples like {:key, value} to support several options.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0