From 7dabefe14b4fe34380efd4bc1741d31684f4685f Mon Sep 17 00:00:00 2001 From: Charles Iliya Krempeaux Date: Tue, 26 Sep 2023 13:41:23 +0900 Subject: [PATCH] initial commits --- field.go | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/field.go b/field.go index bc107ad..53e7947 100644 --- a/field.go +++ b/field.go @@ -3,6 +3,7 @@ package mstdn import ( "encoding/json" + "sourcecode.social/reiver/go-erorr" "sourcecode.social/reiver/go-opt" "sourcecode.social/reiver/go-nul" ) @@ -10,6 +11,11 @@ import ( var _ json.Marshaler = Field{} var _ json.Unmarshaler = &Field{} +const ( + errCannotMashalFieldAsJSONNoName = erorr.Error("cannot marshal mstdn.Field to JSON — no ‘name’ set") + errCannotMashalFieldAsJSONNoValue = erorr.Error("cannot marshal mstdn.Field to JSON — no ‘value’ set") +) + // Field represents a Mastodon API "Field". // // See: @@ -37,13 +43,34 @@ func FieldVerifiedNameValue(when string, name string, value string) Field { func (receiver Field) MarshalJSON() ([]byte, error) { - duplicate := receiver + var data = map[string]interface{}{} - duplicate.VerifiedAt.WhenNothing(func(){ - duplicate.VerifiedAt = nul.Null[string]() - }) + { + val, found := receiver.Name.Get() + if !found { + return nil, errCannotMashalFieldAsJSONNoName + } - return json.Marshal(duplicate) + data["name"] = val + } + { + val, found := receiver.Value.Get() + if !found { + return nil, errCannotMashalFieldAsJSONNoValue + } + + data["value"] = val + } + { + val, found := receiver.VerifiedAt.Get() + if !found { + data["verified_at"] = nil + } else { + data["verified_at"] = val + } + } + + return json.Marshal(data) } func (receiver *Field) UnmarshalJSON(data []byte) error {