-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
67 lines (51 loc) · 1.35 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
package genericscrud
import (
"bytes"
"encoding/json"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type Model[T any] struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
CreatedAt time.Time `bson:"created_at" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
Data T `bson:"inline"`
}
type baseModel struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
CreatedAt time.Time `bson:"created_at" json:"created_at"`
UpdatedAt time.Time `bson:"updated_at" json:"updated_at"`
}
func (m *Model[T]) MarshalJSON() ([]byte, error) {
base := baseModel{
ID: m.ID,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
}
baseData, err := json.Marshal(base)
if err != nil {
return nil, err
}
baseData = bytes.Replace(baseData, []byte("}"), []byte(","), 1)
data, err := json.Marshal(m.Data)
if err != nil {
return nil, err
}
data = bytes.Replace(data, []byte("{"), []byte(""), 1)
return append(baseData, data...), nil
}
func (m *Model[T]) UnmarshalJSON(data []byte) error {
var base baseModel
if err := json.Unmarshal(data, &base); err != nil {
return err
}
var d T
if err := json.Unmarshal(data, &d); err != nil {
return err
}
m.ID = base.ID
m.CreatedAt = base.CreatedAt
m.UpdatedAt = base.UpdatedAt
m.Data = d
return nil
}