-
Notifications
You must be signed in to change notification settings - Fork 0
/
field.go
75 lines (60 loc) · 2.15 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
package modm
import (
"context"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
// DefaultField represents a structure with default fields for MongoDB documents.
type DefaultField struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"_id"`
CreatedAt time.Time `bson:"created_at,omitempty" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at,omitempty" json:"updated_at"`
}
func (df *DefaultField) SetID(id primitive.ObjectID) {
df.ID = id
}
// DefaultUpdatedAt sets the default value for the UpdatedAt field.
func (df *DefaultField) DefaultUpdatedAt() {
df.UpdatedAt = time.Now()
}
// DefaultCreatedAt sets the default value for the CreatedAt field if it's zero.
func (df *DefaultField) DefaultCreatedAt() {
if df.CreatedAt.IsZero() {
df.CreatedAt = time.Now()
}
}
// DefaultID sets the default value for the _id field if it's zero.
func (df *DefaultField) DefaultID() {
if df.ID.IsZero() {
df.ID = primitive.NewObjectID()
}
}
// BeforeInsert is a hook to set default field values before inserting a document.
func (df *DefaultField) BeforeInsert(ctx context.Context) {
df.DefaultID()
df.DefaultCreatedAt()
df.DefaultUpdatedAt()
}
// AfterInsert is a hook to handle actions after inserting a document.
func (df *DefaultField) AfterInsert(ctx context.Context) {}
// BeforeUpdate is a hook to set default field values before updating a document.
func (df *DefaultField) BeforeUpdate(ctx context.Context) {
df.DefaultUpdatedAt()
}
// AfterUpdate is a hook to handle actions after updating a document.
func (df *DefaultField) AfterUpdate(ctx context.Context) {}
// AfterFind is a hook to handle actions after finding a document.
func (df *DefaultField) AfterFind(ctx context.Context) {}
// Uniques returns the unique indexes for the collection.
func (df *DefaultField) Uniques() []string {
return []string{}
}
// Indexes returns the non-unique indexes for the collection.
func (df *DefaultField) Indexes() []string {
return []string{}
}
// Indexes returns the non-unique indexes for the collection.
func (df *DefaultField) IndexModels() []mongo.IndexModel {
return []mongo.IndexModel{}
}