From df4cadf7978b092645e1a6f5ba2479e8011bb0bc Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Thu, 4 Jan 2024 10:33:57 -0500 Subject: [PATCH] refactor: put shared serialization code in private encode method, and update json and msgpack to use it --- metadata/extra.go | 59 +++++++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/metadata/extra.go b/metadata/extra.go index 0d5fec5..423631a 100644 --- a/metadata/extra.go +++ b/metadata/extra.go @@ -8,6 +8,8 @@ import ( "github.com/vmihailenco/msgpack/v5" ) +type jsonData = map[string]interface{} + var names = map[types.MetadataExtension]string{ types.MetadataExtensionLicenses: "licenses", types.MetadataExtensionDonationKeys: "donationKeys", @@ -55,29 +57,12 @@ func NewExtraMetadata(data map[int]interface{}) *ExtraMetadata { } func (em ExtraMetadata) MarshalJSON() ([]byte, error) { - jsonObject := make(map[string]interface{}) - for key, value := range em.Data { - name, ok := names[types.MetadataExtension(key)] - if ok { - if types.MetadataExtension(key) == types.MetadataExtensionUpdateCID { - cid, err := encoding.CIDFromBytes(value.([]byte)) - var cidString string - if err == nil { - cidString, err = cid.ToString() - } - - if err == nil { - jsonObject["updateCID"] = cidString - } else { - jsonObject["updateCID"] = "" - } - } else { - jsonObject[name] = value - } - } + data, err := em.encode() + if err != nil { + return nil, err } - return json.Marshal(jsonObject) + return json.Marshal(data) } func (em *ExtraMetadata) UnmarshalJSON(data []byte) error { @@ -131,5 +116,35 @@ func (em *ExtraMetadata) DecodeMsgpack(dec *msgpack.Decoder) error { } func (em ExtraMetadata) EncodeMsgpack(enc *msgpack.Encoder) error { - return enc.Encode(em.Data) + data, err := em.encode() + if err != nil { + return err + } + + return enc.Encode(data) +} + +func (em ExtraMetadata) encode() (jsonData, error) { + jsonObject := make(map[string]interface{}) + for key, value := range em.Data { + name, ok := names[types.MetadataExtension(key)] + if ok { + if types.MetadataExtension(key) == types.MetadataExtensionUpdateCID { + cid, err := encoding.CIDFromBytes(value.([]byte)) + var cidString string + if err == nil { + cidString, err = cid.ToString() + } + if err == nil { + jsonObject["updateCID"] = cidString + } else { + jsonObject["updateCID"] = "" + } + } else { + jsonObject[name] = value + } + } + } + + return jsonObject, nil }