go-mstdn/field.go

92 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package mstdn
import (
"encoding/json"
"sourcecode.social/reiver/go-erorr"
"sourcecode.social/reiver/go-opt"
"sourcecode.social/reiver/go-nul"
)
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:
// https://docs.joinmastodon.org/entities/Field/
type Field struct {
Name opt.Optional[string] `json:"name"`
Value opt.Optional[string] `json:"value"`
VerifiedAt nul.Nullable[string] `json:"verified_at"`
}
func FieldNameValue(name string, value string) Field {
return Field{
Name: opt.Something(name),
Value: opt.Something(value),
}
}
func FieldVerifiedNameValue(when string, name string, value string) Field {
return Field{
Name: opt.Something(name),
Value: opt.Something(value),
VerifiedAt: nul.Something(when),
}
}
func (receiver Field) MarshalJSON() ([]byte, error) {
var data = map[string]interface{}{}
{
val, found := receiver.Name.Get()
if !found {
return nil, errCannotMashalFieldAsJSONNoName
}
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 {
if nil == receiver {
return errNilReceiver
}
err := json.Unmarshal(data, receiver)
if nil != err {
return err
}
if nul.Null[string]() == receiver.VerifiedAt {
receiver.VerifiedAt = nul.Nothing[string]()
}
return nil
}