forked from Mirrors/jsonapi
add support for pointers to time and if nil put null in json response
This commit is contained in:
parent
fd92bd51ba
commit
438e9b0626
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)
|
||||
|
||||
if fieldValue.Type() == reflect.TypeOf(time.Time{}) {
|
||||
|
||||
var at int64
|
||||
|
||||
if v.Kind() == reflect.Float64 {
|
||||
|
@ -173,6 +172,26 @@ func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node)
|
|||
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 {
|
||||
fieldValue.Set(reflect.ValueOf(int(v.Interface().(float64))))
|
||||
} else {
|
||||
|
|
16
response.go
16
response.go
|
@ -203,6 +203,22 @@ func visitModelNode(model interface{}, sideload bool) (*Node, []*Node, error) {
|
|||
unix := fieldValue.MethodByName("Unix")
|
||||
val := unix.Call(make([]reflect.Value, 0))[0]
|
||||
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 {
|
||||
node.Attributes[args[1]] = fieldValue.Interface()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue