Skip to content

Conversation

@ulissesalmeida
Copy link
Contributor

@ulissesalmeida ulissesalmeida commented Mar 27, 2020

This feature adds the ability to convert to and from protobufs structs and elixir terms.

The ideas are from this issue: #89

Usage:

If you want to transform an automatically a protobuf message to an Elixir term after decoding, you can implement to_elixir function of the Protobuf.Decodable

      defimpl Protobuf.Decodable, for: MyApp.Protobuf.Date do
        def to_elixir(%MyApp.Protobuf.Date{year: year, month: month, day: day}) do
          {:ok, date} = Date.new(year, month, day)
          date
        end
      end
      # later in a decoded message
      proto_message.birthday
      ~D[1988-10-29]

If you want to automatically encode a elixir term to a protobuf message, you can implement the Encodable protocol.

      defimpl Protobuf.Encodable, for: Date do
        def to_protobuf(%Date{year: year, month: month, day: day}, MyApp.Protobuf.Date) do
          MyApp.Protobuf.Date.new(year: year, month: month, day: day)
        end
      end
      # later, you can use Elixir terms in your fields and those will be
      # converted to protobuf structs before binary encoding
      %{protobuf_message | birthday: ~D[1988-10-29]}

Then, if you do this, basically you need to annotate your types differently, then you can annotate your protobuf message with the Elixir message:

       message Date {
         option (elixirpb.message).typespec = "Date.t";
         int iso_days = 1;
       }

test "uses the option type_name" do
file = File.read!("test/protobuf/protoc/proto_gen/extension.pb.ex")

assert file =~ "inserted_at: DateTime.t() | nil\n"
Copy link
Contributor Author

@ulissesalmeida ulissesalmeida Mar 31, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very weak test, but I don't know how is the best way to test generation from protobuf file to elixir file.

@whatyouhide
Copy link
Collaborator

Hey @ulissesalmeida, we decided that we can't take any new code in this library for now since we're trying to get it back in shape and releasing it. We want to keep only the features that we have right now without adding anything for the time being. We'll consider something like this before 1.0 though! Thank you so much 💟

@whatyouhide whatyouhide closed this Jun 7, 2021
hypno2000 added a commit to coingaming/protobuf-elixir that referenced this pull request Sep 12, 2021
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

Successfully merging this pull request may close these issues.

2 participants