Documentation
¶
Index ¶
- func Filter(msg proto.Message, paths []string)
- func Overwrite(src, dest proto.Message, paths []string)
- func PathsFromFieldNumbers(msg proto.Message, fieldNumbers ...int) []string
- func Prune(msg proto.Message, paths []string)
- func Validate(validationModel proto.Message, paths []string) error
- type NestedMask
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Filter ¶
Filter keeps the msg fields that are listed in the paths and clears all the rest.
This is a handy wrapper for NestedMask.Filter method. If the same paths are used to process multiple proto messages use NestedMask.Filter method directly.
Example (Reuse_mask) ¶
ExampleFilter_reuse_mask illustrates how a single NestedMask instance can be used to process multiple proto messages.
package main
import (
"fmt"
"github.com/mennanov/fmutils"
"github.com/mennanov/fmutils/testproto"
)
func main() {
users := []*testproto.User{
{
UserId: 1,
Name: "name 1",
},
{
UserId: 2,
Name: "name 2",
},
}
// Create a mask only once and reuse it.
mask := fmutils.NestedMaskFromPaths([]string{"name"})
for _, user := range users {
mask.Filter(user)
}
fmt.Println(users)
}
Output: [name:"name 1" name:"name 2"]
Example (Update_request) ¶
ExampleFilter_update_request illustrates an API endpoint that updates an existing entity. The request to that endpoint provides a field mask that should be used to update the entity.
package main
import (
"fmt"
"regexp"
"google.golang.org/genproto/protobuf/field_mask"
"google.golang.org/protobuf/proto"
"github.com/mennanov/fmutils"
"github.com/mennanov/fmutils/testproto"
)
var reSpaces = regexp.MustCompile(`\s+`)
func main() {
// Assuming the profile entity is loaded from a database.
profile := &testproto.Profile{
User: &testproto.User{
UserId: 64,
Name: "user name",
},
Photo: &testproto.Photo{
PhotoId: 2,
Path: "photo path",
Dimensions: &testproto.Dimensions{
Width: 100,
Height: 120,
},
},
LoginTimestamps: []int64{1, 2, 3},
}
// An API request from an API user.
updateProfileRequest := &testproto.UpdateProfileRequest{
Profile: &testproto.Profile{
User: &testproto.User{
UserId: 65, // not listed in the field mask, so won't be updated.
Name: "new user name",
},
Photo: &testproto.Photo{
PhotoId: 3, // not listed in the field mask, so won't be updated.
Path: "new photo path",
Dimensions: &testproto.Dimensions{
Width: 50,
},
},
LoginTimestamps: []int64{4, 5}},
Fieldmask: &field_mask.FieldMask{
Paths: []string{"user.name", "photo.path", "photo.dimensions.width", "login_timestamps"}},
}
// Normalize and validate the field mask before using it.
updateProfileRequest.Fieldmask.Normalize()
if !updateProfileRequest.Fieldmask.IsValid(profile) {
// Return an error.
panic("invalid field mask")
}
// Redact the request according to the provided field mask.
fmutils.Filter(updateProfileRequest.GetProfile(), updateProfileRequest.Fieldmask.GetPaths())
// Now that the request is vetted we can merge it with the profile entity.
proto.Merge(profile, updateProfileRequest.GetProfile())
// The profile can now be saved in a database.
fmt.Println(reSpaces.ReplaceAllString(profile.String(), " "))
}
Output: user:{user_id:64 name:"new user name"} photo:{photo_id:2 path:"new photo path" dimensions:{width:50 height:120}} login_timestamps:1 login_timestamps:2 login_timestamps:3 login_timestamps:4 login_timestamps:5
func Overwrite ¶ added in v0.2.1
Overwrite overwrites all the fields listed in paths in the dest msg using values from src msg. Map values are partially merged when the mask addresses nested fields inside the map value.
This is a handy wrapper for NestedMask.Overwrite method. If the same paths are used to process multiple proto messages use NestedMask.Overwrite method directly.
func PathsFromFieldNumbers ¶ added in v0.3.4
PathsFromFieldNumbers converts protobuf field numbers to field paths for the given message.
This function takes a protobuf message and a list of field numbers, and returns a slice of field paths (field names) corresponding to those numbers.
Field numbers that don't exist in the message descriptor are skipped.
If no field numbers are provided, returns nil.
Example:
// For a message with fields: name (field 1), age (field 2), address (field 3) paths := PathsFromFieldNumbers(msg, 1, 2) // Returns: ["name", "age"]
Example ¶
ExamplePathsFromFieldNumbers illustrates how to convert protobuf field numbers to field paths. This is useful when you have field numbers from the protobuf schema and need to convert them to field paths for use with field masks.
package main
import (
"fmt"
"github.com/mennanov/fmutils"
"github.com/mennanov/fmutils/testproto"
)
func main() {
user := &testproto.User{}
// Convert field numbers to field paths.
// Field 1 is "user_id", field 2 is "name"
paths := fmutils.PathsFromFieldNumbers(user, 1, 2)
fmt.Println("Field numbers:", []int{1, 2})
fmt.Println("Paths:", paths)
}
Output: Field numbers: [1 2] Paths: [user_id name]
func Prune ¶
Prune clears all the fields listed in paths from the given msg.
This is a handy wrapper for NestedMask.Prune method. If the same paths are used to process multiple proto messages use NestedMask.Filter method directly.
Types ¶
type NestedMask ¶
type NestedMask map[string]NestedMask
NestedMask represents a field mask as a recursive map.
func NestedMaskFromPaths ¶
func NestedMaskFromPaths(paths []string) NestedMask
NestedMaskFromPaths creates an instance of NestedMask for the given paths.
For example ["foo.bar", "foo.baz"] becomes {"foo": {"bar": nil, "baz": nil}}.
func (NestedMask) Filter ¶
func (mask NestedMask) Filter(msg proto.Message)
Filter keeps the msg fields that are listed in the paths and clears all the rest.
If the mask is empty then all the fields are kept. Paths are assumed to be valid and normalized otherwise the function may panic. See google.golang.org/protobuf/types/known/fieldmaskpb for details.
func (NestedMask) Overwrite ¶ added in v0.2.1
func (mask NestedMask) Overwrite(src, dest proto.Message)
Overwrite overwrites all the fields listed in paths in the dest msg using values from src msg.
All other fields are kept untouched. If the mask is empty, no fields are overwritten. Supports scalars, messages, repeated fields, and maps. If the parent of the field is nil message, the parent is initiated before overwriting the field If the field in src is empty value, the field in dest is cleared. A field overwritten as a whole is assigned, not copied, so dest and src end up sharing that message, list or map; clone src first if it is mutated afterwards. Paths are assumed to be valid and normalized otherwise the function may panic.
func (NestedMask) Prune ¶
func (mask NestedMask) Prune(msg proto.Message)
Prune clears all the fields listed in paths from the given msg.
All other fields are kept untouched. If the mask is empty no fields are cleared. This operation is the opposite of NestedMask.Filter. Paths are assumed to be valid and normalized otherwise the function may panic. See google.golang.org/protobuf/types/known/fieldmaskpb for details.
func (NestedMask) Validate ¶ added in v0.3.5
func (m NestedMask) Validate(validationModel proto.Message) error
Validate checks if all paths are valid for specified message.
Supports scalars, messages, repeated fields, and maps.
A path segment following a map field is treated as a map key, which is always valid since keys are arbitrary. Any deeper segments are validated against the map value message (only possible when the value is a message).