fieldmask.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package runtime
  2. import (
  3. "encoding/json"
  4. "io"
  5. "strings"
  6. descriptor2 "github.com/golang/protobuf/descriptor"
  7. "github.com/golang/protobuf/protoc-gen-go/descriptor"
  8. "google.golang.org/genproto/protobuf/field_mask"
  9. )
  10. func translateName(name string, md *descriptor.DescriptorProto) (string, *descriptor.DescriptorProto) {
  11. // TODO - should really gate this with a test that the marshaller has used json names
  12. if md != nil {
  13. for _, f := range md.Field {
  14. if f.JsonName != nil && f.Name != nil && *f.JsonName == name {
  15. var subType *descriptor.DescriptorProto
  16. // If the field has a TypeName then we retrieve the nested type for translating the embedded message names.
  17. if f.TypeName != nil {
  18. typeSplit := strings.Split(*f.TypeName, ".")
  19. typeName := typeSplit[len(typeSplit)-1]
  20. for _, t := range md.NestedType {
  21. if typeName == *t.Name {
  22. subType = t
  23. }
  24. }
  25. }
  26. return *f.Name, subType
  27. }
  28. }
  29. }
  30. return name, nil
  31. }
  32. // FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.
  33. func FieldMaskFromRequestBody(r io.Reader, md *descriptor.DescriptorProto) (*field_mask.FieldMask, error) {
  34. fm := &field_mask.FieldMask{}
  35. var root interface{}
  36. if err := json.NewDecoder(r).Decode(&root); err != nil {
  37. if err == io.EOF {
  38. return fm, nil
  39. }
  40. return nil, err
  41. }
  42. queue := []fieldMaskPathItem{{node: root, md: md}}
  43. for len(queue) > 0 {
  44. // dequeue an item
  45. item := queue[0]
  46. queue = queue[1:]
  47. if m, ok := item.node.(map[string]interface{}); ok {
  48. // if the item is an object, then enqueue all of its children
  49. for k, v := range m {
  50. protoName, subMd := translateName(k, item.md)
  51. if subMsg, ok := v.(descriptor2.Message); ok {
  52. _, subMd = descriptor2.ForMessage(subMsg)
  53. }
  54. var path string
  55. if item.path == "" {
  56. path = protoName
  57. } else {
  58. path = item.path + "." + protoName
  59. }
  60. queue = append(queue, fieldMaskPathItem{path: path, node: v, md: subMd})
  61. }
  62. } else if len(item.path) > 0 {
  63. // otherwise, it's a leaf node so print its path
  64. fm.Paths = append(fm.Paths, item.path)
  65. }
  66. }
  67. return fm, nil
  68. }
  69. // fieldMaskPathItem stores a in-progress deconstruction of a path for a fieldmask
  70. type fieldMaskPathItem struct {
  71. // the list of prior fields leading up to node connected by dots
  72. path string
  73. // a generic decoded json object the current item to inspect for further path extraction
  74. node interface{}
  75. // descriptor for parent message
  76. md *descriptor.DescriptorProto
  77. }