From 0f1f7809b61518afc138de2f4fa2b5009715ab68 Mon Sep 17 00:00:00 2001 From: atjhoendz Date: Fri, 7 Oct 2022 09:42:59 +0700 Subject: [PATCH] feature: add ParseNatsEventMessageFromBytes --- event_message.go | 7 +++++++ event_message_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/event_message.go b/event_message.go index c1704bc..0c404e5 100644 --- a/event_message.go +++ b/event_message.go @@ -275,6 +275,13 @@ func ParseJSON(in string) (*NatsEventMessage, error) { return msg, err } +// ParseNatsEventMessageFromBytes :nodoc: +func ParseNatsEventMessageFromBytes(in []byte) (*NatsEventMessage, error) { + msg := &NatsEventMessage{} + err := tapao.Unmarshal(in, msg, tapao.With(tapao.JSON)) + return msg, err +} + // ParseNatsEventAuditLogMessageFromBytes :nodoc: func ParseNatsEventAuditLogMessageFromBytes(in []byte) (*NatsEventAuditLogMessage, error) { msg := &NatsEventAuditLogMessage{} diff --git a/event_message_test.go b/event_message_test.go index b0d3ddb..16ff4b8 100644 --- a/event_message_test.go +++ b/event_message_test.go @@ -274,6 +274,23 @@ func TestNatsEventMessage_ParseJSON(t *testing.T) { assert.Equal(t, msg, parsed) } +func TestNatsEventMessage_ParseNatsEventMessageFromBytes(t *testing.T) { + now := time.Now().Format(NatsEventTimeFormat) + json := fmt.Sprintf("{\"NatsEvent\":{\"id\":123,\"user_id\":333,\"tenant_id\":0,\"time\":\"%s\",\"subject\":\"\"},\"body\":\"[\\\"test\\\"]\",\"old_body\":\"\",\"request\":null,\"error\":null}", now) + natsEvent := &NatsEvent{ + ID: 123, + UserID: 333, + Time: now, + } + body := []string{"test"} + msg := NewNatsEventMessage().WithEvent(natsEvent).WithBody(body) + + parsed, err := ParseNatsEventMessageFromBytes([]byte(json)) + require.NoError(t, err) + + assert.Equal(t, msg, parsed) +} + func TestNatsEventAuditLogMessage_Build(t *testing.T) { type User struct { ID int64 `json:"id"`