/
field.go
79 lines (65 loc) · 1.99 KB
/
field.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
package mgm
import (
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// IDField struct contains a model's ID field.
type IDField struct {
ID primitive.ObjectID `json:"id" bson:"_id,omitempty"`
}
// DateFields struct contains the `created_at` and `updated_at`
// fields that autofill when inserting or updating a model.
type DateFields struct {
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}
type DeleteField struct {
Deleted bool `json:"deleted" bson:"deleted"`
DeletedAt time.Time `json:"deleted_at" bson:"deleted_at"`
}
type VersionFeild struct {
Version int64 `json:"version" bson:"version"`
LastVersion int64 `json:"last_version" bson:"last_version"`
}
// PrepareID method prepares the ID value to be used for filtering
// e.g convert hex-string ID value to bson.ObjectId
func (f *IDField) PrepareID(id interface{}) (interface{}, error) {
if idStr, ok := id.(string); ok {
return primitive.ObjectIDFromHex(idStr)
}
// Otherwise id must be ObjectId
return id, nil
}
// GetID method returns a model's ID
func (f *IDField) GetID() interface{} {
return f.ID
}
// SetID sets the value of a model's ID field.
func (f *IDField) SetID(id interface{}) {
f.ID = id.(primitive.ObjectID)
}
//--------------------------------
// DateField methods
//--------------------------------
// Creating hook is used here to set the `created_at` field
// value when inserting a new model into the database.
// TODO: get context as param the next version(4).
func (f *DateFields) Creating() error {
f.CreatedAt = time.Now().UTC()
return nil
}
// Saving hook is used here to set the `updated_at` field
// value when creating or updating a model.
// TODO: get context as param the next version(4).
func (f *DateFields) Saving() error {
f.UpdatedAt = time.Now().UTC()
return nil
}
func (f *DeleteField) SetDeleted(deleted bool) {
f.Deleted = deleted
if deleted {
f.DeletedAt = time.Now().UTC()
} else {
f.DeletedAt = time.Time{}
}
}