View Source Protobuf.Any (protobuf v0.17.0)

Provides functions for working with the google.protobuf.Any type.

Summary

Functions

Packs a Protobuf message into a Google.Protobuf.Any message.

Unpacks a Google.Protobuf.Any message using a custom type provider.

Functions

Link to this function

pack(data)

View Source (since 0.16.0)
@spec pack(struct()) :: Google.Protobuf.Any.t()

Packs a Protobuf message into a Google.Protobuf.Any message.

Example

message = MyPkg.MyMessage.new(%{field: "value"})
any = Protobuf.Any.pack(message)
#=> %Google.Protobuf.Any{
#=>   type_url: "type.googleapis.com/my_pkg.MyMessage",
#=>   value: <<...>>
#=> }
Link to this function

unpack(any, type_provider)

View Source (since 0.17.0)
@spec unpack(Google.Protobuf.Any.t(), module()) ::
  {:ok, struct()} | {:error, reason :: any()}

Unpacks a Google.Protobuf.Any message using a custom type provider.

The type provider module must implement the Protobuf.Any.TypeProvider behaviour, which defines how to convert type URLs to their corresponding message modules.

Example

defmodule MyApp.AnyTypeProvider do
  @behaviour Protobuf.Any.TypeProvider

  def to_module("type.googleapis.com/google.protobuf.Duration"), do: {:ok, Google.Protobuf.Duration}
  def to_module("type.googleapis.com/myapp.events.UserCreated"), do: {:ok, MyApp.Events.UserCreated}
  def to_module("myapp.internal/myapp.events.OrderPlaced"), do: {:ok, MyApp.Events.OrderPlaced}
  def to_module(_), do: {:error, "Unknown type_url"}
end

any = %Google.Protobuf.Any{
  type_url: "type.googleapis.com/myapp.events.UserCreated",
  value: <<...>>
}
Protobuf.Any.unpack(any, MyApp.AnyTypeProvider)
#=> {:ok, %MyApp.Events.UserCreated{...}}