File tree Expand file tree Collapse file tree 2 files changed +46
-2
lines changed
Expand file tree Collapse file tree 2 files changed +46
-2
lines changed Original file line number Diff line number Diff line change 11defmodule Protobuf.Any do
2- @ moduledoc false
2+ @ moduledoc """
3+ Provides functions for working with the `google.protobuf.Any` type.
4+ """
5+
6+ @ type_url_prefix "type.googleapis.com/"
7+
8+ @ doc """
9+ Packs a Protobuf message into a `Google.Protobuf.Any` message.
10+
11+ ## Example
12+
13+ message = MyPkg.MyMessage.new(%{field: "value"})
14+ any = Protobuf.Any.pack(message)
15+ #=> %Google.Protobuf.Any{
16+ #=> type_url: "type.googleapis.com/my_pkg.MyMessage",
17+ #=> value: <<...>>
18+ #=> }
19+
20+ """
21+ @ doc since: "0.16.0"
22+ @ spec pack ( struct ( ) ) :: Google.Protobuf.Any . t ( )
23+ def pack ( % mod { } = data ) do
24+ % Google.Protobuf.Any {
25+ type_url: "#{ @ type_url_prefix } #{ mod . full_name ( ) } " ,
26+ value: mod . encode ( data )
27+ }
28+ end
329
430 @ spec type_url_to_module ( String . t ( ) ) :: module ( )
531 def type_url_to_module ( type_url ) when is_binary ( type_url ) do
632 case type_url do
7- "type.googleapis.com/" <> package_and_message ->
33+ @ type_url_prefix <> package_and_message ->
834 package_and_message
935 |> String . split ( "." )
1036 |> Enum . map ( & Macro . camelize / 1 )
Original file line number Diff line number Diff line change 11defmodule Protobuf.AnyTest do
22 use ExUnit.Case , async: true
33
4+ doctest Protobuf.Any
5+
6+ describe "pack/1" do
7+ test "packs a message into Any" do
8+ message = % Google.Protobuf.Duration { seconds: 42 }
9+ assert % Google.Protobuf.Any { } = result = Protobuf.Any . pack ( message )
10+ assert result . type_url == "type.googleapis.com/google.protobuf.Duration"
11+ assert result . value == Google.Protobuf.Duration . encode ( message )
12+ end
13+
14+ test "packs a message into Any with a prefix" do
15+ message = % My.Test.Request.SomeGroup { group_field: 42 }
16+ assert % Google.Protobuf.Any { } = result = Protobuf.Any . pack ( message )
17+ assert result . type_url == "type.googleapis.com/test.Request.SomeGroup"
18+ assert result . value == My.Test.Request.SomeGroup . encode ( message )
19+ end
20+ end
21+
422 describe "type_url_to_module/1" do
523 test "returns the module for a valid type_url" do
624 assert Protobuf.Any . type_url_to_module ( "type.googleapis.com/google.protobuf.Duration" ) ==
You can’t perform that action at this time.
0 commit comments