Skip to content

Commit d8d7fc6

Browse files
authored
feat(functions/metadata): Special-case marshaling (#2669)
Handle the RawPath element during marshaling in the same way as during unmarshaling.
1 parent 63bfd63 commit d8d7fc6

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

functions/metadata/metadata.go

+18
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,24 @@ func (r *Resource) UnmarshalJSON(data []byte) error {
7777
return nil
7878
}
7979

80+
// MarshalJSON specializes the Resource marshalling to handle the case where the
81+
// value is a string instead of a map. See the comment above on RawPath for why this
82+
// needs to be handled.
83+
func (r *Resource) MarshalJSON() ([]byte, error) {
84+
// If RawPath is set, use that as the whole value.
85+
if r.RawPath != "" {
86+
return []byte(fmt.Sprintf("%q", r.RawPath)), nil
87+
}
88+
89+
// Otherwise, accept whatever the result of the normal marshal would be.
90+
res := *r
91+
b, err := json.Marshal(res)
92+
if err != nil {
93+
return nil, err
94+
}
95+
return b, nil
96+
}
97+
8098
type contextKey string
8199

82100
// GCFContextKey satisfies an interface to be able to use contextKey to read

functions/metadata/metadata_test.go

+52
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,55 @@ func TestUnmarshalJSON(t *testing.T) {
120120
}
121121
}
122122
}
123+
124+
func TestMarshalJSON(t *testing.T) {
125+
ts, err := time.Parse("2006-01-02T15:04:05Z07:00", "2019-11-04T23:01:10.112Z")
126+
if err != nil {
127+
t.Fatalf("Error parsing time: %v.", err)
128+
}
129+
var tests = []struct {
130+
name string
131+
metadata Metadata
132+
want []byte
133+
}{
134+
{
135+
name: "MetadataWithResource",
136+
metadata: Metadata{
137+
EventID: "1234567",
138+
Timestamp: ts,
139+
EventType: "google.pubsub.topic.publish",
140+
Resource: &Resource{
141+
Service: "pubsub.googleapis.com",
142+
Name: "mytopic",
143+
Type: "type.googleapis.com/google.pubsub.v1.PubsubMessage",
144+
},
145+
},
146+
},
147+
{
148+
name: "MetadataWithString",
149+
metadata: Metadata{
150+
EventID: "1234567",
151+
Timestamp: ts,
152+
EventType: "google.pubsub.topic.publish",
153+
Resource: &Resource{
154+
RawPath: "projects/myproject/mytopic",
155+
},
156+
},
157+
},
158+
}
159+
160+
for _, tc := range tests {
161+
b, err := json.Marshal(&tc.metadata)
162+
if err != nil {
163+
t.Errorf("MarshalJSON(%s) error: %v", tc.name, err)
164+
}
165+
166+
var m Metadata
167+
if err := json.Unmarshal(b, &m); err != nil {
168+
t.Errorf("MarshalJSON(%s) error: %v", tc.name, err)
169+
}
170+
if !cmp.Equal(m, tc.metadata) {
171+
t.Errorf("MarshalJSON(%s) error: got %v, want %v", tc.name, m, tc.metadata)
172+
}
173+
}
174+
}

0 commit comments

Comments
 (0)