Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for oneof attributes missing when using JSON? #156

Open
zookzook opened this issue Mar 31, 2022 · 0 comments
Open

Support for oneof attributes missing when using JSON? #156

zookzook opened this issue Mar 31, 2022 · 0 comments

Comments

@zookzook
Copy link

zookzook commented Mar 31, 2022

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.

@zookzook zookzook changed the title Support for oneof attributes missing? Support for oneof attributes missing when using JSON? Mar 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant