/
update.go
155 lines (130 loc) · 2.52 KB
/
update.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package todo
import (
"context"
"net/http"
"time"
"github.com/efreitasn/gtodo/internal/data/template"
"github.com/efreitasn/gtodo/internal/data/user"
"github.com/efreitasn/gtodo/pkg/flash"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var updatePOSTSuccessMsg = &flash.Message{
Content: "Todos updated!",
Kind: 0,
}
var updatePOSTErrorMsg = &flash.Message{
Content: "Error while updating todos.",
Kind: 1,
}
// UpdateGET renders the todos to be updated.
func (t *Todo) UpdateGET(w http.ResponseWriter, r *http.Request) {
tData := template.DataFromContext(r.Context())
tData.Mode = "update"
tData.Title = "Update"
t.fetchDoneNotDone(w, r, tData)
}
// UpdatePOST updates todos.
func (t *Todo) UpdatePOST(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
r.ParseForm()
doneTodosIDs, ok := r.Form["done"]
userPayload := user.PayloadFromContext(r.Context())
filterUserID := bson.E{
Key: "_user",
Value: userPayload.ID,
}
if ok {
// Filter values
filterValue := make(bson.A, len(doneTodosIDs))
for i, doneTodosID := range doneTodosIDs {
oID, err := primitive.ObjectIDFromHex(doneTodosID)
if err != nil {
flash.Add("/update", w, r, updatePOSTErrorMsg)
return
}
filterValue[i] = bson.D{
{
Key: "_id",
Value: oID,
},
}
}
// Update to done = true
filterOr := bson.D{
filterUserID,
{
Key: "$or",
Value: filterValue,
},
}
_, err := t.c.UpdateMany(
ctx,
filterOr,
bson.D{
{
Key: "$set",
Value: bson.D{
{
Key: "done",
Value: true,
},
},
},
},
)
if err != nil {
flash.Add("/update", w, r, updatePOSTErrorMsg)
return
}
// Update to done = false
filterNor := bson.D{
filterUserID,
{
Key: "$nor",
Value: filterValue,
},
}
_, err = t.c.UpdateMany(
ctx,
filterNor,
bson.D{
{
Key: "$set",
Value: bson.D{
{
Key: "done",
Value: false,
},
},
},
},
)
if err != nil {
flash.Add("/update", w, r, updatePOSTErrorMsg)
return
}
} else {
_, err := t.c.UpdateMany(
ctx,
bson.D{filterUserID},
bson.D{
{
Key: "$set",
Value: bson.D{
{
Key: "done",
Value: false,
},
},
},
},
)
if err != nil {
flash.Add("/update", w, r, updatePOSTErrorMsg)
return
}
}
flash.Add("/update", w, r, updatePOSTSuccessMsg)
}