Skip to content

Commit

Permalink
Allow for manually setting the CreatedAt field. (#409)
Browse files Browse the repository at this point in the history
  • Loading branch information
burrows authored and stanislas-m committed Jul 14, 2019
1 parent c6dcf30 commit 42586cb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
8 changes: 6 additions & 2 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,13 @@ func (m *Model) touchCreatedAt() {
now := time.Now()
switch fbn.Kind() {
case reflect.Int, reflect.Int64:
fbn.SetInt(now.Unix())
if fbn.Int() == 0 {
fbn.SetInt(now.Unix())
}
default:
fbn.Set(reflect.ValueOf(now))
if fbn.Interface().(time.Time).IsZero() {
fbn.Set(reflect.ValueOf(now))
}
}
}
}
Expand Down
26 changes: 26 additions & 0 deletions model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,19 @@ func Test_Touch_Time_Timestamp(t *testing.T) {
r.NotZero(v.UpdatedAt)
}

func Test_Touch_Time_Timestamp_With_Existing_Value(t *testing.T) {
r := require.New(t)

createdAt := time.Now().Add(-36 * time.Hour)

m := Model{Value: &TimeTimestamp{CreatedAt: createdAt}}
m.touchCreatedAt()
m.touchUpdatedAt()
v := m.Value.(*TimeTimestamp)
r.Equal(createdAt, v.CreatedAt)
r.NotZero(v.UpdatedAt)
}

func Test_Touch_Unix_Timestamp(t *testing.T) {
r := require.New(t)

Expand All @@ -83,3 +96,16 @@ func Test_Touch_Unix_Timestamp(t *testing.T) {
r.NotZero(v.CreatedAt)
r.NotZero(v.UpdatedAt)
}

func Test_Touch_Unix_Timestamp_With_Existing_Value(t *testing.T) {
r := require.New(t)

createdAt := int(time.Now().Add(-36 * time.Hour).Unix())

m := Model{Value: &UnixTimestamp{CreatedAt: createdAt}}
m.touchCreatedAt()
m.touchUpdatedAt()
v := m.Value.(*UnixTimestamp)
r.Equal(createdAt, v.CreatedAt)
r.NotZero(v.UpdatedAt)
}

0 comments on commit 42586cb

Please sign in to comment.