From 37b3bf7a8aecb4c1681f5a1eafce9c6e6bc1af56 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Thu, 17 Nov 2022 10:58:40 -0300 Subject: [PATCH] helpers for dealing with extra values in events. --- event_extra.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 event_extra.go diff --git a/event_extra.go b/event_extra.go new file mode 100644 index 0000000..6e29d40 --- /dev/null +++ b/event_extra.go @@ -0,0 +1,55 @@ +package nostr + +// SetExtra sets an out-of-the-spec value under the given key into the event object. +func (evt *Event) SetExtra(key string, value any) { + evt.extra[key] = value +} + +// GetExtra tries to get a value under the given key that may be present in the event object +// but is hidden in the basic type since it is out of the spec. +func (evt Event) GetExtra(key string) any { + ival, _ := evt.extra[key] + return ival +} + +// GetExtraString is like [Event.GetExtra], but only works if the value is a string, +// otherwise returns the zero-value. +func (evt Event) GetExtraString(key string) string { + ival, ok := evt.extra[key] + if !ok { + return "" + } + val, ok := ival.(string) + if !ok { + return "" + } + return val +} + +// GetExtraNumber is like [Event.GetExtra], but only works if the value is a float64, +// otherwise returns the zero-value. +func (evt Event) GetExtraNumber(key string) float64 { + ival, ok := evt.extra[key] + if !ok { + return 0 + } + val, ok := ival.(float64) + if !ok { + return 0 + } + return val +} + +// GetExtraBoolean is like [Event.GetExtra], but only works if the value is a boolean, +// otherwise returns the zero-value. +func (evt Event) GetExtraBoolean(key string) bool { + ival, ok := evt.extra[key] + if !ok { + return false + } + val, ok := ival.(bool) + if !ok { + return false + } + return val +}