/
template.go
117 lines (103 loc) · 2.38 KB
/
template.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package database
import (
"context"
"fmt"
"log"
"time"
"github.com/gofrs/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
type DbTemplate struct {
Uuid string
Name string
Json string
CreateAt string
ImageId string
}
type Template struct {
collection *mongo.Collection
}
func (self *Client) Template() *Template {
template := Template{}
if self.database == nil {
return nil
}
template.collection = self.database.Collection("template")
return &template
}
func (self *Template) Add(name, data, imageId string) error {
t := time.Now().Format(time.RFC3339)
u, err := uuid.NewV4()
if err != nil {
return err
}
self.collection.InsertOne(context.TODO(), bson.D{
{"uuid", u.String()},
{"name", name},
{"json", data},
{"createAt", t},
{"imageId", imageId},
})
return nil
}
func (self *Template) Delete(uuid string) error {
// TODO:
// uuid를 통해서 Collection을 탐색한 뒤, imageId 값을 구한 뒤 삭제 해야함
_, err := self.collection.DeleteMany(context.TODO(), bson.D{
{"uuid", uuid},
})
return err
}
func (self *Template) Update(uuid, name, json string) {
self.collection.UpdateOne(context.TODO(), bson.D{
{"uuid", uuid},
}, bson.D{
{"name", name},
{"json", json},
// {"imageId", imageId},
})
}
func (self *Template) Get(uuid string) (DbTemplate, error) {
result := self.collection.FindOne(context.TODO(), bson.D{
{"uuid", uuid},
})
var elem bson.M
err := result.Decode(&elem)
if err != nil {
return DbTemplate{}, fmt.Errorf("데이터를 정상적으로 찾을수가 없음.")
} else {
return DbTemplate{
ImageId: elem["imageId"].(string),
Uuid: elem["uuid"].(string),
Name: elem["name"].(string),
Json: elem["json"].(string),
CreateAt: elem["createAt"].(string),
}, nil
}
}
func (self *Template) List() []DbTemplate {
cursor, err := self.collection.Find(context.TODO(), bson.D{{}})
if err != nil {
log.Println(err)
return []DbTemplate{}
}
db := []DbTemplate{}
for cursor.Next(context.TODO()) {
var elem bson.M
err := cursor.Decode(&elem)
if err != nil {
fmt.Println(err)
}
// find 결과 print
fmt.Println(elem)
db = append(db, DbTemplate{
Uuid: elem["uuid"].(string),
Name: elem["name"].(string),
Json: elem["json"].(string),
CreateAt: elem["createAt"].(string),
ImageId: elem["imageId"].(string),
})
}
return db
}