/
node.go
115 lines (95 loc) · 2.39 KB
/
node.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
package controller
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/brunoos/cnterra-controller/db"
"github.com/brunoos/cnterra-controller/model"
)
type formCreateNode struct {
NodeID int `json:"nodeid"`
Model string `json:"model"`
Attributes map[string]string `json:"attributes"`
}
//------------------------------------------------------------------------------
func GetAllNodes(c *gin.Context) {
col := db.DB.Collection("nodes")
cur, err := col.Find(context.Background(), bson.M{})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error retrieving nodes",
})
return
}
defer cur.Close(context.Background())
nodes := make([]*model.Node, 0)
for cur.Next(context.Background()) {
node := new(model.Node)
if err = cur.Decode(node); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error retrieving nodes",
})
return
}
nodes = append(nodes, node)
}
c.JSON(http.StatusOK, gin.H{
"nodes": nodes,
})
}
func CreateNode(c *gin.Context) {
form := formCreateNode{}
if err := c.Bind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "invalid parameters",
})
return
}
if len(form.Model) == 0 || form.NodeID <= 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "invalid parameters",
})
return
}
node := model.Node{
ID: primitive.NewObjectID(),
NodeID: form.NodeID,
Model: form.Model,
Attributes: form.Attributes,
}
col := db.DB.Collection("nodes")
if _, err := col.InsertOne(context.Background(), &node); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error creating a new node",
})
return
}
c.JSON(http.StatusCreated, &node)
}
func DeleteNode(c *gin.Context) {
param := c.Param("id")
id, err := primitive.ObjectIDFromHex(param)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "invalid node ID",
})
return
}
col := db.DB.Collection("nodes")
res, err := col.DeleteOne(context.Background(), bson.M{"_id": id})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "error deleting the node",
})
return
}
if res.DeletedCount == 0 {
c.JSON(http.StatusNotFound, gin.H{
"message": "node not found",
})
return
}
c.Status(http.StatusOK)
}