Skip to content

Commit

Permalink
Add EmitDefault option for ProtoJson converter (#1286)
Browse files Browse the repository at this point in the history
  • Loading branch information
vbmithr authored Oct 31, 2023
1 parent 3cccbdd commit 0352634
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions converter/proto_json_payload_converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import (
type ProtoJSONPayloadConverter struct {
gogoMarshaler gogojsonpb.Marshaler
gogoUnmarshaler gogojsonpb.Unmarshaler
protoMarshalOptions protojson.MarshalOptions
protoUnmarshalOptions protojson.UnmarshalOptions
options ProtoJSONPayloadConverterOptions
}
Expand All @@ -53,6 +54,16 @@ type ProtoJSONPayloadConverterOptions struct {

// AllowUnknownFields will ignore unknown fields when unmarshalling, as opposed to returning an error
AllowUnknownFields bool

// UseProtoNames uses proto field name instead of lowerCamelCase name in JSON
// field names.
UseProtoNames bool

// UseEnumNumbers emits enum values as numbers.
UseEnumNumbers bool

// EmitUnpopulated specifies whether to emit unpopulated fields.
EmitUnpopulated bool
}

var (
Expand All @@ -64,17 +75,27 @@ func NewProtoJSONPayloadConverter() *ProtoJSONPayloadConverter {
return &ProtoJSONPayloadConverter{
gogoMarshaler: gogojsonpb.Marshaler{},
gogoUnmarshaler: gogojsonpb.Unmarshaler{},
protoMarshalOptions: protojson.MarshalOptions{},
protoUnmarshalOptions: protojson.UnmarshalOptions{},
}
}

// NewProtoJSONPayloadConverterWithOptions creates new instance of `ProtoJSONPayloadConverter` with the provided options.
func NewProtoJSONPayloadConverterWithOptions(options ProtoJSONPayloadConverterOptions) *ProtoJSONPayloadConverter {
return &ProtoJSONPayloadConverter{
gogoMarshaler: gogojsonpb.Marshaler{},
gogoMarshaler: gogojsonpb.Marshaler{
EnumsAsInts: options.UseEnumNumbers,
EmitDefaults: options.EmitUnpopulated,
OrigName: options.UseProtoNames,
},
gogoUnmarshaler: gogojsonpb.Unmarshaler{
AllowUnknownFields: options.AllowUnknownFields,
},
protoMarshalOptions: protojson.MarshalOptions{
UseProtoNames: options.UseProtoNames,
UseEnumNumbers: options.UseEnumNumbers,
EmitUnpopulated: options.EmitUnpopulated,
},
protoUnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: options.AllowUnknownFields,
},
Expand All @@ -101,7 +122,7 @@ func (c *ProtoJSONPayloadConverter) ToPayload(value interface{}) (*commonpb.Payl
builtPointer := false
for {
if valueProto, ok := value.(proto.Message); ok {
byteSlice, err := protojson.Marshal(valueProto)
byteSlice, err := c.protoMarshalOptions.Marshal(valueProto)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrUnableToEncode, err)
}
Expand Down

0 comments on commit 0352634

Please sign in to comment.