✨ Some convenience methods for Metas
This commit is contained in:
parent
8086029b03
commit
79fa957d02
4 changed files with 39 additions and 16 deletions
|
|
@ -1,21 +1,15 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
//"bufio"
|
||||
//"bytes"
|
||||
"encoding/json"
|
||||
//"fmt"
|
||||
//"errors"
|
||||
//"regexp"
|
||||
//"strings"
|
||||
//"sync"
|
||||
"time"
|
||||
//"codeberg.org/danjones000/my-log/tools"
|
||||
)
|
||||
|
||||
// A slice of Meta
|
||||
type Metas []Meta
|
||||
|
||||
func (ms Metas) toMap() map[string]any {
|
||||
// Returns a single map containing all the Meta. Is useful when encoding to JSON
|
||||
func (ms Metas) Map() map[string]any {
|
||||
out := map[string]any{}
|
||||
for _, f := range ms {
|
||||
if _, found := out[f.Key]; found || f.Key == "title" || f.Key == "date" {
|
||||
|
|
@ -42,12 +36,14 @@ func (ms Metas) toMap() map[string]any {
|
|||
return out
|
||||
}
|
||||
|
||||
// Implements json.Marshaler
|
||||
func (ms Metas) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(ms.toMap())
|
||||
return json.Marshal(ms.Map())
|
||||
}
|
||||
|
||||
// Implements json.Unmarshaler
|
||||
func (ms *Metas) UnmarshalJSON(in []byte) error {
|
||||
old := (*ms).toMap()
|
||||
old := (*ms).Map()
|
||||
out := map[string]any{}
|
||||
err := json.Unmarshal(in, &out)
|
||||
if err != nil {
|
||||
|
|
@ -62,3 +58,14 @@ func (ms *Metas) UnmarshalJSON(in []byte) error {
|
|||
*ms = ret
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns a new Metas with a new Meta appended
|
||||
func (ms Metas) Append(k string, v any) Metas {
|
||||
return append(ms, Meta{k, v})
|
||||
}
|
||||
|
||||
// Appends a new Meta to this Metas
|
||||
func (ms *Metas) AppendTo(k string, v any) {
|
||||
n := (*ms).Append(k, v)
|
||||
*ms = n
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue