mennanov / fmutils

Golang protobuf FieldMask missing utils
MIT License
109 stars 11 forks source link

Add Overwrite function #8

Closed elb3k closed 1 year ago

elb3k commented 1 year ago

Add the Override function which will override the values in destination message using source message fields (filtered by paths)

mennanov commented 1 year ago

It should be possible to use the proto.Merge() function https://github.com/protocolbuffers/protobuf-go/blob/8088bf85b8fc5a6c0d7e2a39743e237cae8bef99/proto/merge.go#L25 to achieve a similar result. Is there a reason you decided to add this function?

elb3k commented 1 year ago

It should be possible to use the proto.Merge() function https://github.com/protocolbuffers/protobuf-go/blob/8088bf85b8fc5a6c0d7e2a39743e237cae8bef99/proto/merge.go#L25 to achieve a similar result. Is there a reason you decided to add this function?

Yes proto.Merge() can be used to achieve a similar result. But it only overrides filled fields (no 0, empty string nor nil message/list/map) But this function only overrides the values set in the update mask and it supports empty values as well.

elb3k commented 1 year ago

My primary use case for this function is to override proto with a PATCH request. proto.Merge works 95% of the time, but it does not distinguish between not set and set with zero value (0 for int, empty string for string field). Example:

Source message:

src := &testproto.Message{
  IntField: 32,
  StringField: "string",
  ListField: []string{"a", "b", "c"},
}

PATCH request:

patch := &testproto.Message{
  IntField: 0,
  StringField: "",
  ListField: []string{},
}

patchPaths := []string{"int_field", "string_field", "list_field"}

proto.Merge will not override those values, but the Override function will override every field that is in the patchPaths

codecov[bot] commented 1 year ago

Codecov Report

Merging #8 (9c443c5) into main (d05c935) will decrease coverage by 1.58%. The diff coverage is 93.93%.

@@             Coverage Diff             @@
##              main       #8      +/-   ##
===========================================
- Coverage   100.00%   98.42%   -1.58%     
===========================================
  Files            1        1              
  Lines           94      127      +33     
===========================================
+ Hits            94      125      +31     
- Misses           0        1       +1     
- Partials         0        1       +1     
Files Coverage Δ
fmutils.go 98.42% <93.93%> (-1.58%) :arrow_down:

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

mennanov commented 1 year ago

Thanks a lot!