/
mapper_static.go
50 lines (42 loc) · 1.14 KB
/
mapper_static.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package msgqueue
import (
"encoding/json"
"fmt"
"github.com/martin-helmich/cloudnativego-backend/src/contracts"
"github.com/mitchellh/mapstructure"
)
type StaticEventMapper struct{}
func (e *StaticEventMapper) MapEvent(eventName string, serialized interface{}) (Event, error) {
var event Event
switch eventName {
case "eventCreated":
event = &contracts.EventCreatedEvent{}
case "locationCreated":
event = &contracts.LocationCreatedEvent{}
case "eventBooked":
event = &contracts.EventBookedEvent{}
default:
return nil, fmt.Errorf("unknown event type %s", eventName)
}
switch s := serialized.(type) {
case []byte:
err := json.Unmarshal(s, event)
if err != nil {
return nil, fmt.Errorf("could not unmarshal event %s: %s", eventName, err)
}
default:
cfg := mapstructure.DecoderConfig{
Result: event,
TagName: "json",
}
dec, err := mapstructure.NewDecoder(&cfg)
if err != nil {
return nil, fmt.Errorf("could not initialize decoder for event %s: %s", eventName, err)
}
err = dec.Decode(s)
if err != nil {
return nil, fmt.Errorf("could not unmarshal event %s: %s", eventName, err)
}
}
return event, nil
}