Skip to content

Commit

Permalink
feat (serializer) StringToMap and MapToString
Browse files Browse the repository at this point in the history
  • Loading branch information
pentateu committed Apr 16, 2020
1 parent eda4a8b commit 9da6339
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
28 changes: 28 additions & 0 deletions serializer/jsonSerializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package serializer

import (
"bytes"
"encoding/json"
"errors"
"io"

"sort"
"strconv"
"time"
Expand Down Expand Up @@ -59,6 +61,32 @@ func (serializer JSONSerializer) ReaderToPayload(r io.Reader) moleculer.Payload
return payload
}

//MapToString serialize a map into a string
//This implementation uses the standard library json pkg and it needs to be compared with others for performance.
//Performance: it should be experimented with multiple implementations. This is just he initial one.
func (serializer JSONSerializer) MapToString(m interface{}) string {
r, err := json.Marshal(m)
if err != nil {
serializer.logger.Errorln("Error trying to serialize a map. error: ", err)
panic(err)
}
s := string(r)
return s
}

//StringToMap deserialize a string (json) into map
//Same implementation and performance notes as MapToString
func (serializer JSONSerializer) StringToMap(j string) map[string]interface{} {
m := map[string]interface{}{}
err := json.Unmarshal([]byte(j), &m)
if err != nil {
serializer.logger.Errorln("Error trying to deserialize a map from json: " + j)
serializer.logger.Errorln("error: ", err)
panic(err)
}
return m
}

func (serializer JSONSerializer) PayloadToBytes(payload moleculer.Payload) []byte {
return []byte(serializer.PayloadToString(payload))
}
Expand Down
5 changes: 4 additions & 1 deletion serializer/serializer.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package serializer

import (
"github.com/moleculer-go/moleculer"
"io"

"github.com/moleculer-go/moleculer"
)

type Serializer interface {
ReaderToPayload(io.Reader) moleculer.Payload
BytesToPayload(*[]byte) moleculer.Payload
PayloadToBytes(moleculer.Payload) []byte
PayloadToString(moleculer.Payload) string
MapToString(interface{}) string
StringToMap(string) map[string]interface{}
PayloadToContextMap(moleculer.Payload) map[string]interface{}
MapToPayload(*map[string]interface{}) (moleculer.Payload, error)
}
Expand Down

0 comments on commit 9da6339

Please sign in to comment.