planner/item/event.go

89 lines
1.6 KiB
Go
Raw Normal View History

2024-09-20 07:09:30 +02:00
package item
import (
"encoding/json"
"fmt"
"time"
)
type EventBody struct {
2024-09-26 07:21:48 +02:00
Title string `json:"title"`
Start time.Time `json:"start"`
Duration time.Duration `json:"duration"`
2024-09-20 07:09:30 +02:00
}
func (e EventBody) MarshalJSON() ([]byte, error) {
type Alias EventBody
return json.Marshal(&struct {
2024-09-26 07:21:48 +02:00
Start string `json:"start"`
Duration string `json:"duration"`
2024-09-20 07:09:30 +02:00
*Alias
}{
2024-09-26 07:21:48 +02:00
Start: e.Start.UTC().Format(time.RFC3339),
Duration: e.Duration.String(),
Alias: (*Alias)(&e),
2024-09-20 07:09:30 +02:00
})
}
2024-09-26 07:21:48 +02:00
func (e *EventBody) UnmarshalJSON(data []byte) error {
type Alias EventBody
aux := &struct {
Start string `json:"start"`
Duration string `json:"duration"`
*Alias
}{
Alias: (*Alias)(e),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var err error
if e.Start, err = time.Parse(time.RFC3339, aux.Start); err != nil {
return err
}
if e.Duration, err = time.ParseDuration(aux.Duration); err != nil {
return err
}
return nil
}
2024-09-20 07:09:30 +02:00
type Event struct {
ID string `json:"id"`
EventBody
}
func NewEvent(i Item) (Event, error) {
if i.Kind != KindEvent {
return Event{}, fmt.Errorf("item is not an event")
}
var e Event
if err := json.Unmarshal([]byte(i.Body), &e); err != nil {
return Event{}, fmt.Errorf("could not unmarshal item body: %v", err)
}
e.ID = i.ID
return e, nil
}
func (e Event) Item() (Item, error) {
body, err := json.Marshal(EventBody{
2024-09-26 07:21:48 +02:00
Title: e.Title,
Start: e.Start,
Duration: e.Duration,
2024-09-20 07:09:30 +02:00
})
if err != nil {
return Item{}, fmt.Errorf("could not marshal event to json")
}
return Item{
ID: e.ID,
Kind: KindEvent,
Body: string(body),
}, nil
}