add an "extra" map to events that can be used to merge other properties when necessary.

This commit is contained in:
fiatjaf 2022-11-04 08:21:35 -03:00
parent fb3972b725
commit 3a6d6795e4
No known key found for this signature in database
GPG Key ID: BAD43C4BE5C1A3A1
2 changed files with 17 additions and 0 deletions

View File

@ -19,6 +19,9 @@ type Event struct {
Tags Tags
Content string
Sig string
// anything here will be mashed together with the main event object when serializing
extra map[string]any
}
const (

View File

@ -57,6 +57,9 @@ func (evt *Event) UnmarshalJSON(payload []byte) error {
return fmt.Errorf("event is not an object")
}
// prepare this to receive any extra property that may serialized along with the event
evt.extra = make(map[string]any)
var visiterr error
obj.Visit(func(k []byte, v *fastjson.Value) {
key := string(k)
@ -102,6 +105,10 @@ func (evt *Event) UnmarshalJSON(payload []byte) error {
visiterr = fmt.Errorf("invalid 'sig' field: %w", err)
}
evt.Sig = string(id)
default:
var anyValue any
json.Unmarshal(v.MarshalTo(nil), anyValue)
evt.extra[key] = anyValue
}
})
if visiterr != nil {
@ -123,6 +130,13 @@ func (evt Event) MarshalJSON() ([]byte, error) {
o.Set("content", arena.NewString(evt.Content))
o.Set("sig", arena.NewString(evt.Sig))
for k, v := range evt.extra {
b, _ := json.Marshal(v)
if val, err := fastjson.ParseBytes(b); err == nil {
o.Set(k, val)
}
}
return o.MarshalTo(nil), nil
}