refactor: put shared serialization code in private encode method, and update json and msgpack to use it

This commit is contained in:
Derrick Hammer 2024-01-04 10:33:57 -05:00
parent c5441b2e16
commit df4cadf797
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 37 additions and 22 deletions

View File

@ -8,6 +8,8 @@ import (
"github.com/vmihailenco/msgpack/v5" "github.com/vmihailenco/msgpack/v5"
) )
type jsonData = map[string]interface{}
var names = map[types.MetadataExtension]string{ var names = map[types.MetadataExtension]string{
types.MetadataExtensionLicenses: "licenses", types.MetadataExtensionLicenses: "licenses",
types.MetadataExtensionDonationKeys: "donationKeys", types.MetadataExtensionDonationKeys: "donationKeys",
@ -55,29 +57,12 @@ func NewExtraMetadata(data map[int]interface{}) *ExtraMetadata {
} }
func (em ExtraMetadata) MarshalJSON() ([]byte, error) { func (em ExtraMetadata) MarshalJSON() ([]byte, error) {
jsonObject := make(map[string]interface{}) data, err := em.encode()
for key, value := range em.Data { if err != nil {
name, ok := names[types.MetadataExtension(key)] return nil, err
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 json.Marshal(jsonObject) return json.Marshal(data)
} }
func (em *ExtraMetadata) UnmarshalJSON(data []byte) error { 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 { 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
} }