protomask

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 4 Imported by: 0

README

protomask GoDoc Github release Test status

protomask is a package that lets you update protobuf messages with a help of field masks.

Features

  • Assign values from one message to another based on a field mask.
  • Create a mask of all populated fields of a message.
  • Supports nested fields, and handles their parent being nil.
  • Supports fieldmaskpb, including oneof properties.

Installation

go get github.com/olexnzarov/protomask

Usage

func (s *BookServer) UpdateBookPrice(id int64, priceCents int64) error {
  update := &pb.Book{
    Id: id,
    Price: &pb.Price{
      Cents: priceCents,
    },
  }
  mask, _ := fieldmaskpb.New(update, "price.cents")
  return s.UpdateBook(update, mask)
}

func (s *BookServer) UpdateBook(update *pb.Book, updateMask protomask.FieldMask) error {
  book, err := s.bookStorage.GetById(update.Id)
  if err != nil {
    return err
  }
  err = protomask.Update(book, update, updateMask)
  if err != nil {
    return err
  }
  return s.bookStorage.Save(book)
}

Examples

See protomask_test.go for more examples on how to use the package. Also, you can check out gofu for a real-life example of how it can be used.

License

This code is available under the MIT license, allowing for free use, modification, and distribution.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidFieldMask = errors.New("invalid field mask")
View Source
var ErrInvalidPath = errors.New("invalid path")

Functions

func Update

func Update[T protoreflect.ProtoMessage](targetMessage T, updateMessage T, updateMask FieldMask) error

Update updates the targetMessage with values from the updateMessage, updateMask specifies which fields need to be updated.

FieldMask should contain field names like in .proto file. Nested paths are supported (e.g. "foo.bar.xyz"). If nested field's parent is a nil value, it will be initialized with a default value. Nested paths inside a map are not supported.

See the following package for a FieldMask implementation: https://google.golang.org/protobuf/types/known/fieldmaskpb

Types

type FieldMask

type FieldMask interface {
	GetPaths() []string
	IsValid(protoreflect.ProtoMessage) bool
}

func All

func All[T protoreflect.ProtoMessage](message T) FieldMask

All returns a field mask that contains all populated fields from the given message. It will only contain shallow fields from the root of the message, no nested ones.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL