✨ Entry implements json.Marshaler
This commit is contained in:
parent
7e1c51d698
commit
f3bf89b09e
2 changed files with 22 additions and 2 deletions
|
|
@ -3,6 +3,7 @@ package models
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
@ -157,5 +158,23 @@ func (e *Entry) getFieldUnarshalChan(in []byte) chan Meta {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e Entry) MarshalJSON() ([]byte, error) {
|
func (e Entry) MarshalJSON() ([]byte, error) {
|
||||||
return []byte(`{}`), nil
|
if e.Title == "" {
|
||||||
|
return []byte{}, ErrorMissingTitle
|
||||||
|
}
|
||||||
|
if e.Date == (time.Time{}) {
|
||||||
|
return []byte{}, ErrorMissingDate
|
||||||
|
}
|
||||||
|
|
||||||
|
out := map[string]any{}
|
||||||
|
out["title"] = e.Title
|
||||||
|
out["date"] = e.Date.Format(time.RFC3339)
|
||||||
|
for _, f := range e.Fields {
|
||||||
|
if _, ok := out[f.Key]; !ok {
|
||||||
|
out[f.Key] = f.Value
|
||||||
|
if vt, ok := f.Value.(time.Time); ok {
|
||||||
|
out[f.Key] = vt.Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return json.Marshal(out)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -191,7 +191,7 @@ func TestScan(t *testing.T) {
|
||||||
|
|
||||||
func TestEntryJsonMarshal(t *testing.T) {
|
func TestEntryJsonMarshal(t *testing.T) {
|
||||||
when := time.Now()
|
when := time.Now()
|
||||||
whens := when.Format(DateFormat)
|
whens := when.Format(time.RFC3339)
|
||||||
simple := []Meta{}
|
simple := []Meta{}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|
@ -210,6 +210,7 @@ func TestEntryJsonMarshal(t *testing.T) {
|
||||||
{"empty-title", "", when, simple, "", ErrorMissingTitle},
|
{"empty-title", "", when, simple, "", ErrorMissingTitle},
|
||||||
{"empty-date", "A Title", time.Time{}, simple, "", ErrorMissingDate},
|
{"empty-date", "A Title", time.Time{}, simple, "", ErrorMissingDate},
|
||||||
{"obj-field", "A Title", when, []Meta{{"obj", json.RawMessage(`{"foo":"bar","title":"Sub-title"}`)}}, `{"title":"A Title","date":"` + whens + `","obj":{"foo":"bar","title":"Sub-title"}}`, nil},
|
{"obj-field", "A Title", when, []Meta{{"obj", json.RawMessage(`{"foo":"bar","title":"Sub-title"}`)}}, `{"title":"A Title","date":"` + whens + `","obj":{"foo":"bar","title":"Sub-title"}}`, nil},
|
||||||
|
{"date-field", "A Title", when, []Meta{{"when", when.Add(time.Hour)}}, `{"title":"A Title","date":"` + whens + `","when":"` + when.Add(time.Hour).Format(time.RFC3339) + `"}`, nil},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue