Skip to content

Commit

Permalink
Fix Date object unmarshalling
Browse files Browse the repository at this point in the history
Notion API can return date from page fields in the form of "yyyy-mm-dd"
if the field configuration does not include time. The resulting string from the API
isn't accepted by the time.RFC3339 format and thus causes an unmarshalling
error.

The present change fixes it by attempting to parse it as such in case
the standard format fails. If it fails again, the error is returned.
  • Loading branch information
jhchabran authored and jomei committed Aug 30, 2021
1 parent 555bf21 commit 8ad477e
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
25 changes: 24 additions & 1 deletion object.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package notionapi

import "time"
import (
"time"
)

type ObjectType string

Expand Down Expand Up @@ -73,6 +75,27 @@ func (d Date) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}

func (d *Date) UnmarshalText(data []byte) error {
t, err := time.Parse(time.RFC3339, string(data))

// Because the API does not distinguish between datetime with a
// timezone and dates, we eventually have to try both.
if err != nil {
if _, ok := err.(*time.ParseError); !ok {
return err
} else {
t, err = time.Parse("2006-01-02", string(data)) // Date
if err != nil {
// Still cannot parse it, nothing else to try.
return err
}
}
}

*d = Date(t)
return nil
}

type File struct {
Name string `json:"name"`
}
Expand Down
35 changes: 35 additions & 0 deletions object_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package notionapi_test

import (
"testing"

"github.com/jomei/notionapi"
)

func TestDate(t *testing.T) {
t.Run(".UnmarshalText", func(t *testing.T) {
var d notionapi.Date

t.Run("OK datetime with timezone", func(t *testing.T) {
data := []byte("1987-02-13T00:00:00.000+01:00")
err := d.UnmarshalText(data)
if err != nil {
t.Fatal(err)
}
})
t.Run("OK date", func(t *testing.T) {
data := []byte("1985-01-02")
err := d.UnmarshalText(data)
if err != nil {
t.Fatal(err)
}
})
t.Run("NOK", func(t *testing.T) {
data := []byte("1985")
err := d.UnmarshalText(data)
if err == nil {
t.Fatalf("expected an error, got none")
}
})
})
}

0 comments on commit 8ad477e

Please sign in to comment.