Skip to content

Commit

Permalink
Add custom JSON marshallers to cache data
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbanham committed Mar 4, 2021
1 parent 33659d4 commit 9f1ba98
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
37 changes: 37 additions & 0 deletions notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package notifications

import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"text/template"
Expand Down Expand Up @@ -109,6 +111,41 @@ func (attachment Attachment) execute(data io.Writer) error {
return err
}

func (attachment *Attachment) MarshalJSON() ([]byte, error) {
data, err := ioutil.ReadAll(attachment.Data)
if err != nil {
return []byte{}, err
}

return json.Marshal(&struct {
ContentType string `json:"content_type"`
Data []byte `json:"data"`
Filename string `json:"filename"`
}{
ContentType: attachment.ContentType,
Data: data,
Filename: attachment.Filename,
})
}

func (attachment *Attachment) UnmarshalJSON(data []byte) error {
inner := struct {
ContentType string `json:"content_type"`
Data []byte `json:"data"`
Filename string `json:"filename"`
}{}

if err := json.Unmarshal(data, &inner); err != nil {
return err
}

attachment.ContentType = inner.ContentType
attachment.Filename = inner.Filename
attachment.Data = bytes.NewReader(inner.Data)

return nil
}

func SendEmail(email Email) error {
if debugLogging {
log.Printf("DEBUG notifications email: %+v \n", email)
Expand Down
35 changes: 35 additions & 0 deletions notifications_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package notifications

import (
"encoding/json"
"io/ioutil"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestNotificationsLive(t *testing.T) {
Expand Down Expand Up @@ -41,3 +45,34 @@ func TestNotificationsWithAttachmentsLive(t *testing.T) {
t.Fatal(err)
}
}

func TestJSONMarshalAndUnmarshal(t *testing.T) {
data := strings.NewReader("oh hi I am an attachment")

email := Email{
To: "david@banham.id.au",
From: "testrun@takehome.io",
ReplyTo: "lolwut@takehome.io",
Text: "this is the text part of a test run",
HTML: "this <i>is the HTML part of a test</i> run",
Subject: "test run",
Attachments: []Attachment{
Attachment{
ContentType: "text/plain",
Data: data,
Filename: "test_data.txt",
},
},
}

result, err := json.Marshal(email)
assert.Nil(t, err)

newEmail := Email{}

assert.Nil(t, json.Unmarshal(result, &newEmail))

contents, err := ioutil.ReadAll(newEmail.Attachments[0].Data)
assert.Nil(t, err)
assert.Equal(t, string(contents), "oh hi I am an attachment")
}

0 comments on commit 9f1ba98

Please sign in to comment.