-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.go
81 lines (64 loc) · 1.7 KB
/
model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package scores
import (
"time"
)
// Model adds an auto assignable ID to models.
type Model interface {
SetID(id int)
}
// M is an entity with a primary key `ID` that gets auto
// assigned by the repository when set.
type M struct {
ID int `json:"id" db:"id"`
}
// SetID sets the ID on the model
func (m *M) SetID(id int) {
m.ID = id
}
// Tracked adds Created / Updated / Deleted metadata to models.
type Tracked interface {
Create(when time.Time) Tracked
Update(when time.Time) Tracked
Delete(when time.Time) Tracked
MockUpdates(when *time.Time)
}
// Track adds timestamps `CreatedAt`, `UpdatedAt`,
// `DeletedAt` to the model.
type Track struct {
CreatedAt time.Time `json:"createdAt" db:"created_at"`
UpdatedAt *time.Time `json:"updatedAt" db:"updated_at"`
DeletedAt *time.Time `json:"-" db:"deleted_at"`
mockTime *time.Time
}
// Create sets the `CreatedAt` and `UpdatedAt` fields.
func (t *Track) Create(when time.Time) Tracked {
if t.mockTime != nil {
when = *t.mockTime
}
t.CreatedAt = when
return t
}
// Update sets the `UpdatedAt` field.
func (t *Track) Update(when time.Time) Tracked {
if t.mockTime != nil {
when = *t.mockTime
}
t.UpdatedAt = &when
return t
}
// Delete sets the `DeletedAt` field.
func (t *Track) Delete(when time.Time) Tracked {
if t.mockTime != nil {
when = *t.mockTime
}
t.DeletedAt = &when
return t
}
/* --- METHODS FOR TESTING ONLY--- */
// MockUpdates sets mockTime which overrides the arguments
// to other Set* functions and allows us to test the structs
// by equality which otherwise would not be possible (because)
// CreatesAt, UpdatedAt and DeletedAt are set in Repository functions.
func (t *Track) MockUpdates(time *time.Time) {
t.mockTime = time
}