diff --git a/pttodo/schedule.go b/pttodo/schedule.go index 2cc18cd..6c3de04 100644 --- a/pttodo/schedule.go +++ b/pttodo/schedule.go @@ -1,3 +1,13 @@ package pttodo +import "encoding/json" + type Schedule string + +func (schedule Schedule) MarshalJSON() ([]byte, error) { + return json.Marshal(string(schedule)) +} + +func (schedule *Schedule) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, (*string)(schedule)) +} diff --git a/pttodo/schedule_test.go b/pttodo/schedule_test.go new file mode 100644 index 0000000..846f853 --- /dev/null +++ b/pttodo/schedule_test.go @@ -0,0 +1,47 @@ +package pttodo + +import ( + "bytes" + "encoding/json" + "testing" +) + +func TestJSONSchedule(t *testing.T) { + cases := map[string]struct { + input string + wantMarshalled string + }{ + "cron": { + input: "* * * * *", + wantMarshalled: `"* * * * *"`, + }, + "int": { + input: "123", + wantMarshalled: `"123"`, + }, + "duration": { + input: "1h", + wantMarshalled: `"1h"`, + }, + } + + for name, d := range cases { + c := d + t.Run(name, func(t *testing.T) { + gotMarshalled, err := json.Marshal(Schedule(c.input)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal([]byte(c.wantMarshalled), gotMarshalled) { + t.Fatal(c.wantMarshalled, gotMarshalled) + } + var got Schedule + if err := json.Unmarshal(gotMarshalled, &got); err != nil { + t.Fatal(err) + } + if string(got) != c.input { + t.Fatal(got) + } + }) + } +} diff --git a/pttodo/ts.go b/pttodo/ts.go index 4eebf9a..737a4c3 100644 --- a/pttodo/ts.go +++ b/pttodo/ts.go @@ -1,3 +1,19 @@ package pttodo -type TS string +import ( + "encoding/json" + "time" +) + +type TS int64 + +func (ts TS) MarshalJSON() ([]byte, error) { + if ts == 0 { + ts = TS(time.Now().Unix()) + } + return json.Marshal(int64(ts)) +} + +func (ts *TS) UnmarshalJSON(b []byte) error { + return json.Unmarshal(b, (*int64)(ts)) +} diff --git a/pttodo/ts_test.go b/pttodo/ts_test.go new file mode 100644 index 0000000..23dc44f --- /dev/null +++ b/pttodo/ts_test.go @@ -0,0 +1,30 @@ +package pttodo + +import ( + "encoding/json" + "testing" + "time" +) + +func TestJSONTS(t *testing.T) { + ts := TS(time.Now().Unix()) + js, err := json.Marshal(ts) + if err != nil { + t.Fatal(err) + } + + var ts2 TS + if err := json.Unmarshal(js, &ts2); err != nil { + t.Fatal(err) + } + if ts != ts2 { + t.Fatal(ts2) + } + + if err := json.Unmarshal([]byte(`123`), &ts2); err != nil { + t.Fatal(err) + } + if 123 != ts2 { + t.Fatal(ts2) + } +}