forked from Mirrors/jsonapi
Merge pull request #17 from shwoodard/nil-times
add support for pointers to time and if nil put null in json response
This commit is contained in:
commit
53c7c4e5b5
21
request.go
21
request.go
|
@ -154,7 +154,6 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
|
||||||
v := reflect.ValueOf(val)
|
v := reflect.ValueOf(val)
|
||||||
|
|
||||||
if fieldValue.Type() == reflect.TypeOf(time.Time{}) {
|
if fieldValue.Type() == reflect.TypeOf(time.Time{}) {
|
||||||
|
|
||||||
var at int64
|
var at int64
|
||||||
|
|
||||||
if v.Kind() == reflect.Float64 {
|
if v.Kind() == reflect.Float64 {
|
||||||
|
@ -173,6 +172,26 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if fieldValue.Type() == reflect.TypeOf(new(time.Time)) {
|
||||||
|
var at int64
|
||||||
|
|
||||||
|
if v.Kind() == reflect.Float64 {
|
||||||
|
at = int64(v.Interface().(float64))
|
||||||
|
} else if v.Kind() == reflect.Int {
|
||||||
|
at = v.Int()
|
||||||
|
} else {
|
||||||
|
er = errors.New("Only numbers can be parsed as dates, unix timestamps")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
v := time.Unix(at, 0)
|
||||||
|
t := &v
|
||||||
|
|
||||||
|
fieldValue.Set(reflect.ValueOf(t))
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
if fieldValue.Kind() == reflect.Int && v.Kind() == reflect.Float64 {
|
if fieldValue.Kind() == reflect.Int && v.Kind() == reflect.Float64 {
|
||||||
fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64))))
|
fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64))))
|
||||||
} else {
|
} else {
|
||||||
|
|
16
response.go
16
response.go
|
@ -203,6 +203,22 @@ func visitModelNode(model interface{}, sideload bool) (*Node, []*Node, error) {
|
||||||
unix := fieldValue.MethodByName("Unix")
|
unix := fieldValue.MethodByName("Unix")
|
||||||
val := unix.Call(make([]reflect.Value, 0))[0]
|
val := unix.Call(make([]reflect.Value, 0))[0]
|
||||||
node.Attributes[args[1]] = val.Int()
|
node.Attributes[args[1]] = val.Int()
|
||||||
|
} else if fieldValue.Type() == reflect.TypeOf(new(time.Time)) {
|
||||||
|
// A time pointer may be nil
|
||||||
|
t := reflect.ValueOf(fieldValue.Interface())
|
||||||
|
if t.IsNil() {
|
||||||
|
node.Attributes[args[1]] = nil
|
||||||
|
} else {
|
||||||
|
isZeroMethod := fieldValue.MethodByName("IsZero")
|
||||||
|
isZero := isZeroMethod.Call(make([]reflect.Value, 0))[0].Interface().(bool)
|
||||||
|
if isZero {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
unix := fieldValue.MethodByName("Unix")
|
||||||
|
val := unix.Call(make([]reflect.Value, 0))[0]
|
||||||
|
node.Attributes[args[1]] = val.Int()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
node.Attributes[args[1]] = fieldValue.Interface()
|
node.Attributes[args[1]] = fieldValue.Interface()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue