Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC 3339 support for both Marshal and Unmarshal. #204

Merged
merged 7 commits into from
Apr 5, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions constants.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package jsonapi

import "time"

const (
// StructTag annotation strings
annotationJSONAPI = "jsonapi"
Expand All @@ -9,8 +11,10 @@ const (
annotationRelation = "relation"
annotationOmitEmpty = "omitempty"
annotationISO8601 = "iso8601"
annotationRFC3339 = "rfc3339"
annotationSeperator = ","

rfc3339TimeFormat = time.RFC3339
iso8601TimeFormat = "2006-01-02T15:04:05Z"

// MediaType is the identifier for the JSON API media type
Expand Down
12 changes: 8 additions & 4 deletions models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,14 @@ type WithPointer struct {
FloatVal *float32 `jsonapi:"attr,float-val"`
}

type Timestamp struct {
ID int `jsonapi:"primary,timestamps"`
Time time.Time `jsonapi:"attr,timestamp,iso8601"`
Next *time.Time `jsonapi:"attr,next,iso8601"`
type TimestampModel struct {
ID int `jsonapi:"primary,timestamps"`
DefaultV time.Time `jsonapi:"attr,defaultv"`
DefaultP *time.Time `jsonapi:"attr,defaultp"`
ISO8601V time.Time `jsonapi:"attr,iso8601v,iso8601"`
ISO8601P *time.Time `jsonapi:"attr,iso8601p,iso8601"`
RFC3339V time.Time `jsonapi:"attr,rfc3339v,rfc3339"`
RFC3339P *time.Time `jsonapi:"attr,rfc3339p,rfc3339"`
}

type Car struct {
Expand Down
31 changes: 28 additions & 3 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ var (
// ErrInvalidISO8601 is returned when a struct has a time.Time type field and includes
// "iso8601" in the tag spec, but the JSON value was not an ISO8601 timestamp string.
ErrInvalidISO8601 = errors.New("Only strings can be parsed as dates, ISO8601 timestamps")
// ErrInvalidRFC3339 is returned when a struct has a time.Time type field and includes
// "rfc3339" in the tag spec, but the JSON value was not an RFC3339 timestamp string.
ErrInvalidRFC3339 = errors.New("Only strings can be parsed as dates, RFC3339 timestamps")
// ErrUnknownFieldNumberType is returned when the JSON value was a float
// (numeric) but the Struct field was a non numeric type (i.e. not int, uint,
// float, etc)
Expand Down Expand Up @@ -445,18 +448,20 @@ func handleStringSlice(attribute interface{}) (reflect.Value, error) {
}

func handleTime(attribute interface{}, args []string, fieldValue reflect.Value) (reflect.Value, error) {
var isIso8601 bool
var isISO8601, isRFC3339 bool
v := reflect.ValueOf(attribute)

if len(args) > 2 {
for _, arg := range args[2:] {
if arg == annotationISO8601 {
isIso8601 = true
isISO8601 = true
} else if arg == annotationRFC3339 {
isRFC3339 = true
}
}
}

if isIso8601 {
if isISO8601 {
var tm string
if v.Kind() == reflect.String {
tm = v.Interface().(string)
Expand All @@ -476,6 +481,26 @@ func handleTime(attribute interface{}, args []string, fieldValue reflect.Value)
return reflect.ValueOf(t), nil
}

if isRFC3339 {
var tm string
if v.Kind() == reflect.String {
tm = v.Interface().(string)
} else {
return reflect.ValueOf(time.Now()), ErrInvalidRFC3339
}

t, err := time.Parse(time.RFC3339, tm)
if err != nil {
return reflect.ValueOf(time.Now()), ErrInvalidRFC3339
}

if fieldValue.Kind() == reflect.Ptr {
return reflect.ValueOf(&t), nil
}

return reflect.ValueOf(t), nil
}
aren55555 marked this conversation as resolved.
Show resolved Hide resolved

var at int64

if v.Kind() == reflect.Float64 {
Expand Down
225 changes: 163 additions & 62 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package jsonapi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
Expand Down Expand Up @@ -341,75 +342,175 @@ func TestUnmarshalSetsAttrs(t *testing.T) {
}
}

func TestUnmarshalParsesISO8601(t *testing.T) {
payload := &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"timestamp": "2016-08-17T08:27:12Z",
func TestUnmarshal_Times(t *testing.T) {
aren55555 marked this conversation as resolved.
Show resolved Hide resolved
aTime := time.Date(2016, 8, 17, 8, 27, 12, 0, time.UTC)

for _, tc := range []struct {
desc string
inputPayload *OnePayload
wantErr bool
verifcation func(tm *TimestampModel) error
aren55555 marked this conversation as resolved.
Show resolved Hide resolved
}{
// Default:
{
desc: "default_byValue",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"defaultv": aTime.Unix(),
},
},
},
verifcation: func(tm *TimestampModel) error {
if !tm.DefaultV.Equal(aTime) {
return errors.New("times not equal!")
}
return nil
},
},
}

in := bytes.NewBuffer(nil)
json.NewEncoder(in).Encode(payload)

out := new(Timestamp)

if err := UnmarshalPayload(in, out); err != nil {
t.Fatal(err)
}

expected := time.Date(2016, 8, 17, 8, 27, 12, 0, time.UTC)

if !out.Time.Equal(expected) {
t.Fatal("Parsing the ISO8601 timestamp failed")
}
}

func TestUnmarshalParsesISO8601TimePointer(t *testing.T) {
payload := &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"next": "2016-08-17T08:27:12Z",
{
desc: "default_byPointer",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"defaultp": aTime.Unix(),
},
},
},
verifcation: func(tm *TimestampModel) error {
if !tm.DefaultP.Equal(aTime) {
return errors.New("times not equal!")
}
return nil
},
},
}

in := bytes.NewBuffer(nil)
json.NewEncoder(in).Encode(payload)

out := new(Timestamp)

if err := UnmarshalPayload(in, out); err != nil {
t.Fatal(err)
}

expected := time.Date(2016, 8, 17, 8, 27, 12, 0, time.UTC)

if !out.Next.Equal(expected) {
t.Fatal("Parsing the ISO8601 timestamp failed")
}
}

func TestUnmarshalInvalidISO8601(t *testing.T) {
payload := &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"timestamp": "17 Aug 16 08:027 MST",
{
desc: "default_invalid",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"defaultv": "not a timestamp!",
},
},
},
wantErr: true,
},
}

in := bytes.NewBuffer(nil)
json.NewEncoder(in).Encode(payload)

out := new(Timestamp)
// ISO 8601:
{
desc: "iso8601_byValue",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"iso8601v": "2016-08-17T08:27:12Z",
},
},
},
verifcation: func(tm *TimestampModel) error {
if !tm.ISO8601V.Equal(aTime) {
return errors.New("times not equal!")
}
return nil
},
},
{
desc: "iso8601_byPointer",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"iso8601p": "2016-08-17T08:27:12Z",
},
},
},
verifcation: func(tm *TimestampModel) error {
if !tm.ISO8601P.Equal(aTime) {
return errors.New("times not equal!")
}
return nil
},
},
{
desc: "iso8601_invalid",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"iso8601v": "not a timestamp",
},
},
},
wantErr: true,
},
// RFC 3339
{
desc: "rfc3339_byValue",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"rfc3339v": "2016-08-17T08:27:12Z",
},
},
},
verifcation: func(tm *TimestampModel) error {
if got, want := tm.RFC3339V, aTime; got != want {
return fmt.Errorf("got %v, want %v", got, want)
}
return nil
},
},
{
desc: "rfc3339_byPointer",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"rfc3339p": "2016-08-17T08:27:12Z",
},
},
},
verifcation: func(tm *TimestampModel) error {
if got, want := *tm.RFC3339P, aTime; got != want {
return fmt.Errorf("got %v, want %v", got, want)
}
return nil
},
},
{
desc: "rfc3339_invalid",
inputPayload: &OnePayload{
Data: &Node{
Type: "timestamps",
Attributes: map[string]interface{}{
"rfc3339v": "not a timestamp",
},
},
},
wantErr: true,
},
} {
t.Run(tc.desc, func(t *testing.T) {
// Serialize the OnePayload using the standard JSON library.
in := bytes.NewBuffer(nil)
if err := json.NewEncoder(in).Encode(tc.inputPayload); err != nil {
t.Fatal(err)
}

if err := UnmarshalPayload(in, out); err != ErrInvalidISO8601 {
t.Fatalf("Expected ErrInvalidISO8601, got %v", err)
out := &TimestampModel{}
err := UnmarshalPayload(in, out)
if got, want := (err != nil), tc.wantErr; got != want {
t.Fatalf("UnmarshalPayload error: got %v, want %v", got, want)
}
if tc.verifcation != nil {
if err := tc.verifcation(out); err != nil {
t.Fatal(err)
}
}
})
}
}

Expand Down
8 changes: 7 additions & 1 deletion response.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ func visitModelNode(model interface{}, included *map[string]*Node,
node.ClientID = clientID
}
} else if annotation == annotationAttribute {
var omitEmpty, iso8601 bool
var omitEmpty, iso8601, rfc3339 bool

if len(args) > 2 {
for _, arg := range args[2:] {
Expand All @@ -292,6 +292,8 @@ func visitModelNode(model interface{}, included *map[string]*Node,
omitEmpty = true
case annotationISO8601:
iso8601 = true
case annotationRFC3339:
rfc3339 = true
}
}
}
Expand All @@ -309,6 +311,8 @@ func visitModelNode(model interface{}, included *map[string]*Node,

if iso8601 {
node.Attributes[args[1]] = t.UTC().Format(iso8601TimeFormat)
} else if rfc3339 {
node.Attributes[args[1]] = t.UTC().Format(rfc3339TimeFormat)
} else {
node.Attributes[args[1]] = t.Unix()
}
Expand All @@ -329,6 +333,8 @@ func visitModelNode(model interface{}, included *map[string]*Node,

if iso8601 {
node.Attributes[args[1]] = tm.UTC().Format(iso8601TimeFormat)
} else if rfc3339 {
node.Attributes[args[1]] = tm.UTC().Format(rfc3339TimeFormat)
} else {
node.Attributes[args[1]] = tm.Unix()
}
Expand Down
Loading