-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
198 lines (175 loc) · 5.43 KB
/
function.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package gcp_mongo_sless
import (
"context"
"encoding/json"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)
type Workout struct {
Id string `json:"_id" bson:"_id,omitempty"`
Record int64 `json:"record"`
Sets int `json:"sets"`
Comments string `json:"comments"`
CreationDate time.Time `json:"creation_date" bson:"creation_date"`
WorkoutDate string `json:"workout_date" bson:"workout_date"`
Day string `json:"day"`
Week int `json:"week"`
WorkoutType string `json:"workout_type" bson:"workout_type"`
Month string `json:"month"`
Year int `json:"year"`
}
type WorkoutDto struct {
Sets string `json:"sets"`
Comments string `json:"comments"`
WorkoutDate string `json:"workout_date" bson:"workout_date"`
WorkoutType string `json:"workout_type" bson:"workout_type"`
}
func init() {
functions.HTTP("createWorkout", createWorkout)
}
func createWorkout(wr http.ResponseWriter, req *http.Request) {
header := wr.Header()
//wr.Header().Add("Access-Control-Allow-Origin", "https://workouts-web-static.vercel.app")
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
header.Add("Access-Control-Max-Age", "600")
header.Add("Accept", "application/json")
// methods
// GET
if req.Method == "GET" {
_, err := fmt.Fprint(wr, "GET not supported")
if err != nil {
log.Printf("> Error when returing GET response: %v", err)
}
// PUT
} else if req.Method == "PUT" {
var workout Workout
if err := json.NewDecoder(req.Body).Decode(&workout); err != nil {
log.Printf(">>> Error decoding JSON: %v", err)
log.Panicln(err)
}
uri := os.Getenv("MONGODB_URI")
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("workouts").Collection("workouts")
wDate := req.URL.Query().Get("workout_date")
wType := req.URL.Query().Get("workout_type")
// filter
var existingWrkt Workout
filter := bson.D{{"workout_date", wDate}, {"workout_type", wType}}
coll.FindOne(context.TODO(), filter).Decode(&existingWrkt)
// data
var sets, week int
var comments, workDate, workType, day, month string
if workout.WorkoutDate != "" {
workDate = workout.WorkoutDate
} else {
workDate = existingWrkt.WorkoutDate
}
if workout.Sets != 0 {
sets = workout.Sets
} else {
sets = existingWrkt.Sets
}
if workout.Comments != "" {
comments = workout.Comments
} else {
comments = existingWrkt.Comments
}
if workout.WorkoutType != "" {
workType = workout.WorkoutType
} else {
workType = existingWrkt.WorkoutType
}
if workout.Day != "" {
day = workout.Day
} else {
day = existingWrkt.Day
}
if workout.Month != "" {
month = workout.Month
} else {
month = existingWrkt.Month
}
if workout.Week != 0 {
week = workout.Week
} else {
week = existingWrkt.Week
}
updatedWorkut := bson.D{{"$set", bson.D{
{"workout_date", workDate},
{"sets", sets}, {"comments", comments}, {"workout_type", workType},
{"day", day}, {"month", month}, {"week", week}}}}
uddateRes, err2 := coll.UpdateOne(context.TODO(), filter, updatedWorkut)
if err2 != nil {
log.Panicln(err2)
}
fmt.Fprintf(wr, "Updated workout %s", uddateRes.UpsertedID)
// POST
} else if req.Method == "POST" {
var workout WorkoutDto
if err := json.NewDecoder(req.Body).Decode(&workout); err != nil {
log.Printf(">>> Error decoding JSON: %v", err)
log.Panicln(err)
}
uri := os.Getenv("MONGODB_URI")
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err := client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("workouts").Collection("workouts")
wDateDate, err := time.Parse(time.DateOnly, workout.WorkoutDate)
wyear, wWeek := wDateDate.ISOWeek()
sets, err := strconv.Atoi(workout.Sets)
doc := bson.D{
{"record", time.Now().Unix()},
{"sets", sets},
{"workout_date", workout.WorkoutDate},
//{"creation_date", time.Now().Format(time.RFC1123)},
{"creation_date", time.Now()},
{"workout_type", workout.WorkoutType},
{"comments", workout.Comments},
{"day", wDateDate.Weekday().String()},
{"week", wWeek},
{"month", time.Now().Month().String()},
{"year", wyear},
}
//time.Parse(time.RFC822, fmt.Sprintf("01 %s %s 00:00 MST", month[0:3], year[2:4])) //RFC822 = "02 Jan 06 15:04 MST"
res, err := coll.InsertOne(context.TODO(), doc)
// todo: delete debug
bodyJson, err := io.ReadAll(req.Body)
if err != nil {
log.Printf("> Error when reading Insert reply data. %v", err)
}
fmt.Println(string(bodyJson))
//wr.Header().Set("Content-Type", "application/json")
//_, err2 := fmt.Fprintf(wr, "Created workout with _id: %v\n", res.InsertedID)
_, err2 := fmt.Fprintf(wr, "{ \"created_id\": \"%s\" }", res.InsertedID)
if err2 != nil {
log.Printf(">> Error when writing parsed JSON: %v", err2)
}
}
}