Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert protobuf message to map after applying a field mask doesn't work #41

Closed
marcoshuck opened this issue Jan 22, 2024 · 6 comments
Closed

Comments

@marcoshuck
Copy link
Contributor

marcoshuck commented Jan 22, 2024

Context

I'm trying to convert a proto message to map using this library in order to perform a PATCH update in an endpoint. I'm getting an empty map instead of a single field map with the respective value.

Relevant code

mask := &fieldmaskpb.FieldMask{Paths: []string{"title"}}
mask.Normalize()
task := &tasksv1.Task{
  Title: "test",
}
if !mask.IsValid(task) {
  return nil, errors.New("invalid mask")
}
protoMask, err := fieldmask_utils.MaskFromProtoFieldMask(mask, func(s string) string { return s })
if err != nil {
  return nil, err
}
m := make(map[string]any)
if err = fieldmask_utils.StructToMap(protoMask, task, m); err != nil {
  return nil, err
}
fmt.Println("Map:", m)

Current behavior

m is empty

Expected behavior

m := map[string]any{
  "title": "test",
}

Reference

Protobuf messages: https://github.com/marcoshuck/todo/blob/main/api/tasks/v1/tasks.proto#L60

@marcoshuck
Copy link
Contributor Author

@mennanov any chances you can take a look at this?

@mennanov
Copy link
Owner

I'll take a look within the next few days

@mennanov
Copy link
Owner

I wrote a similar test that passes:

func TestTitleBug(t *testing.T) {
	mask := &fieldmaskpb.FieldMask{Paths: []string{"title"}}
	mask.Normalize()
	task := &testproto.Task{
		Title: "test",
	}
	require.True(t, mask.IsValid(task))
	protoMask, err := fieldmask_utils.MaskFromProtoFieldMask(mask, func(s string) string { return generator.CamelCase(s) })
	require.Nil(t, err)
	m := make(map[string]any)
	err = fieldmask_utils.StructToMap(protoMask, task, m)
	require.Nil(t, err)
	assert.Equal(t, map[string]any{"Title": "test"}, m)
}

Try using generator.CamelCase(s) which converts a lower case field name (in the field mask) into a camel case (golang struct naming).

@marcoshuck
Copy link
Contributor Author

marcoshuck commented Jan 30, 2024

Thanks for the information, will give it a try! We should probably add this test case as it would help future devs that find this issue.

I can take care of creating a PR for this test and adding some docs about the generator package (which I was completely unaware of).

@mennanov
Copy link
Owner

A PR is welcomed!

@mennanov
Copy link
Owner

Resolved in PR #42

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

No branches or pull requests

2 participants