Skip to content

Commit 2eeda24

Browse files
committed
use interface to access field
1 parent 10b0033 commit 2eeda24

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

validate.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
package analytics
22

3-
func getString(msg map[string]interface{}, field string) string {
4-
val, _ := msg[field].(string)
5-
return val
3+
type FieldGetter interface {
4+
GetField(field string) (interface{}, bool)
65
}
76

8-
func ValidateFields(msg map[string]interface{}) error {
9-
if typ, ok := msg["type"].(string); ok {
10-
switch typ {
7+
func getString(msg FieldGetter, field string) string {
8+
if val, ok := msg.GetField(field); ok {
9+
if str, ok := val.(string); ok {
10+
return str
11+
}
12+
}
13+
return ""
14+
}
15+
16+
func ValidateFields(msg FieldGetter) error {
17+
typ, _ := msg.GetField("type")
18+
if str, ok := typ.(string); ok {
19+
switch str {
1120
case "alias":
1221
return Alias{
1322
Type: "alias",
@@ -51,6 +60,6 @@ func ValidateFields(msg map[string]interface{}) error {
5160
return FieldError{
5261
Type: "analytics.Event",
5362
Name: "Type",
54-
Value: msg["type"],
63+
Value: typ,
5564
}
5665
}

validate_test.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,19 @@ import (
66
)
77

88
var _ Message = (Event)(nil)
9+
var _ FieldGetter = (Event)(nil)
910

1011
type Event map[string]interface{}
1112

1213
func (e Event) Validate() error {
1314
return ValidateFields(e)
1415
}
1516

17+
func (e Event) GetField(field string) (val interface{}, ok bool) {
18+
val, ok = e[field]
19+
return
20+
}
21+
1622
func TestValidateFieldsMissingType(t *testing.T) {
1723
msg := Event{
1824
"userId": "user123",
@@ -73,7 +79,6 @@ func TestValidateFieldsAliasInvalid(t *testing.T) {
7379
t.Error("validating an invalid generic message succeeded:", msg)
7480
} else if e, ok := err.(FieldError); !ok {
7581
t.Error("invalid error type returned when validating a generic message:", err)
76-
7782
} else if e != (FieldError{
7883
Type: "analytics.Alias",
7984
Name: "PreviousId",

0 commit comments

Comments
 (0)