-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig_student_course_ref.go
371 lines (326 loc) · 11.7 KB
/
config_student_course_ref.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
var studentCourseRefConfigHandlerTable = map[string]gin.HandlerFunc{
"get": studentCourseRefGetHandler,
"post": studentCourseRefPostHandler,
"put": studentCourseRefPutHandler,
"delete": studentCourseRefDeleteHandler,
}
func studentCourseRefGetHandler(ctx *gin.Context) {
// params := ginContextRequestParameter(ctx)
response := GinResponse{
Status: http.StatusOK,
}
defer func() {
ginContextProcessResponse(ctx, &response)
}()
var references []*StudentCourseRef
var err error
var studentPID primitive.ObjectID
var coursePID primitive.ObjectID
sPID := ctx.Request.URL.Query().Get("student_pid")
if sPID == "all" {
studentPID = primitive.NilObjectID
} else {
studentPID, err = primitive.ObjectIDFromHex(sPID)
if err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - Please specifiy a valid student PID (student_pid=?)", serverErrorMessages[seInputParamNotValid])
return
}
}
cPID := ctx.Request.URL.Query().Get("course_pid")
if cPID == "all" {
coursePID = primitive.NilObjectID
} else {
coursePID, err = primitive.ObjectIDFromHex(cPID)
if err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - Please specifiy a valid course PID (course_pid=?)", serverErrorMessages[seInputParamNotValid])
return
}
}
// pid: nil objectid for all, others for specified one
references, err = findStudentCourseRef(studentPID, coursePID)
if err != nil {
response.Status = http.StatusConflict
response.Message = err.Error()
return
}
response.Payload = references
return
}
func studentCourseRefPostHandler(ctx *gin.Context) {
params := ginContextRequestParameter(ctx)
response := GinResponse{
Status: http.StatusOK,
}
defer func() {
ginContextProcessResponse(ctx, &response)
}()
var reference StudentCourseRef
var referencePID primitive.ObjectID
var err error
if err = json.Unmarshal(params.Data, &reference); err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - %s", serverErrorMessages[seInputJSONNotValid], err.Error())
return
}
referencePID, err = createStudentCourseRef(&reference)
if err != nil {
response.Status = http.StatusConflict
response.Message = err.Error()
} else {
response.Payload = referencePID
}
return
}
func studentCourseRefPutHandler(ctx *gin.Context) {
params := ginContextRequestParameter(ctx)
response := GinResponse{
Status: http.StatusOK,
}
defer func() {
ginContextProcessResponse(ctx, &response)
}()
var reference StudentCourseRef
var err error
if err = json.Unmarshal(params.Data, &reference); err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - %s", serverErrorMessages[seInputJSONNotValid], err.Error())
return
}
err = updateStudentCourseRef(&reference)
if err != nil {
response.Status = http.StatusConflict
response.Message = err.Error()
} else {
response.Payload = reference.PID
}
return
}
func studentCourseRefDeleteHandler(ctx *gin.Context) {
// params := ginContextRequestParameter(ctx)
response := GinResponse{
Status: http.StatusOK,
}
defer func() {
ginContextProcessResponse(ctx, &response)
}()
var err error
var deletedRows int
var studentPID primitive.ObjectID
var coursePID primitive.ObjectID
sPID := ctx.Request.URL.Query().Get("student_pid")
if sPID == "all" {
studentPID = primitive.NilObjectID
} else {
studentPID, err = primitive.ObjectIDFromHex(sPID)
if err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - Please specifiy a valid student PID (pid=?)", serverErrorMessages[seInputParamNotValid])
return
}
}
cPID := ctx.Request.URL.Query().Get("course_pid")
if cPID == "all" {
coursePID = primitive.NilObjectID
} else {
coursePID, err = primitive.ObjectIDFromHex(cPID)
if err != nil {
response.Status = http.StatusBadRequest
response.Message = fmt.Sprintf("[%s] - Please specifiy a valid course PID (sid=?)", serverErrorMessages[seInputParamNotValid])
return
}
}
// pid: nil objectid for all, others for specified one
deletedRows, err = deleteStudentCourseRef(studentPID, coursePID)
if err != nil {
response.Status = http.StatusConflict
response.Message = err.Error()
return
}
response.Payload = deletedRows
return
}
// find student-course references, return references slice, error
func findStudentCourseRef(studentPID primitive.ObjectID, coursePID primitive.ObjectID) ([]*StudentCourseRef, error) {
var err error
defer func() {
if err != nil {
logging.Errormf(logModReferenceMgmt, err.Error())
}
}()
var findOptions = options.Find()
var findFilter bson.D = bson.D{}
if !studentPID.IsZero() {
findFilter = append(findFilter, bson.E{"student_pid", studentPID})
}
if !coursePID.IsZero() {
findFilter = append(findFilter, bson.E{"course_pid", coursePID})
}
findCursor, err := dbPool.Collection(DBCollectionStudentCourseRef).Find(context.TODO(), findFilter, findOptions)
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return nil, err
}
references := []*StudentCourseRef{}
for findCursor.Next(context.TODO()) {
var reference StudentCourseRef
err = findCursor.Decode(&reference)
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return nil, err
}
references = append(references, &reference)
}
err = findCursor.Err()
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return nil, err
}
logging.Debugmf(logModReferenceMgmt, "Found %d student-course reference results from DB (studentPID=%v, coursePID=%v)",
len(references), studentPID.Hex(), coursePID.Hex())
return references, nil
}
// create student-course reference, return PID, error
func createStudentCourseRef(reference *StudentCourseRef) (primitive.ObjectID, error) {
var err error
defer func() {
if err != nil {
logging.Errormf(logModReferenceMgmt, err.Error())
}
}()
// student PID check
if reference.StudentPID.IsZero() {
err = fmt.Errorf("[%s] - No student PID specified", serverErrorMessages[seResourceNotFound])
return primitive.NilObjectID, err
}
students, err := findStudent(reference.StudentPID)
if err != nil || len(students) == 0 {
err = fmt.Errorf("[%s] - No students found with PID %s", serverErrorMessages[seResourceNotFound], reference.StudentPID.Hex())
return primitive.NilObjectID, err
}
// course PID check
if reference.CoursePID.IsZero() {
err = fmt.Errorf("[%s] - No course PID specified", serverErrorMessages[seResourceNotFound])
return primitive.NilObjectID, err
}
courses, err := findCourse(reference.CoursePID)
if err != nil || len(courses) == 0 {
err = fmt.Errorf("[%s] - No courses found with PID %s", serverErrorMessages[seResourceNotFound], reference.CoursePID.Hex())
return primitive.NilObjectID, err
}
insertResult, err := dbPool.Collection(DBCollectionStudentCourseRef).InsertOne(context.TODO(), reference)
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return primitive.NilObjectID, err
}
lastInsertID := insertResult.InsertedID.(primitive.ObjectID)
logging.Debugmf(logModReferenceMgmt, "Created student-course reference in DB (LastInsertID,PID=%s)", lastInsertID.Hex())
return lastInsertID, nil
}
// update student-course reference, return error
func updateStudentCourseRef(reference *StudentCourseRef) error {
var err error
defer func() {
if err != nil {
logging.Errormf(logModReferenceMgmt, err.Error())
}
}()
// reference PID check
if reference.PID.IsZero() {
err = fmt.Errorf("[%s] - student-course reference PID is empty", serverErrorMessages[seInputJSONNotValid])
return err
}
// student PID check
if reference.StudentPID.IsZero() {
err = fmt.Errorf("[%s] - No student PID specified", serverErrorMessages[seResourceNotFound])
return err
}
students, err := findStudent(reference.StudentPID)
if err != nil || len(students) == 0 {
err = fmt.Errorf("[%s] - No students found with PID %s", serverErrorMessages[seResourceNotFound], reference.StudentPID.Hex())
return err
}
// course PID check
if reference.CoursePID.IsZero() {
err = fmt.Errorf("[%s] - No course PID specified", serverErrorMessages[seResourceNotFound])
return err
}
courses, err := findCourse(reference.CoursePID)
if err != nil || len(courses) == 0 {
err = fmt.Errorf("[%s] - No courses found with PID %s", serverErrorMessages[seResourceNotFound], reference.CoursePID.Hex())
return err
}
// update student
var updateFilter = bson.D{{"_id", reference.PID}}
var updateBSONDocument = bson.D{}
referenceBSONData, err := bson.Marshal(reference)
if err != nil {
err = fmt.Errorf("[%s] - could not convert student-course reference (PID %s) to bson data", serverErrorMessages[seInputBSONNotValid], reference.PID.Hex())
return err
}
err = bson.Unmarshal(referenceBSONData, &updateBSONDocument)
if err != nil {
err = fmt.Errorf("[%s] - could not convert student-course reference (PID %s) to bson document", serverErrorMessages[seInputBSONNotValid], reference.PID.Hex())
return err
}
var updateOptions = bson.D{{"$set", updateBSONDocument}}
insertResult, err := dbPool.Collection(DBCollectionStudentCourseRef).UpdateOne(context.TODO(), updateFilter, updateOptions)
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return err
}
logging.Debugmf(logModReferenceMgmt, "Update student-course reference (PID %s): matched %d modified %d",
reference.PID.Hex(), insertResult.MatchedCount, insertResult.ModifiedCount)
if insertResult.MatchedCount == 0 {
err = fmt.Errorf("[%s] - could not find student-course reference (PID %s)", serverErrorMessages[seResourceNotFound], reference.PID.Hex())
return err
} else if insertResult.ModifiedCount == 0 {
err = fmt.Errorf("[%s] - student-course reference (PID %s) not changed", serverErrorMessages[seResourceNotChange], reference.PID.Hex())
return err
}
return nil
}
// delete student-course reference, return #delete entries, error
func deleteStudentCourseRef(studentPID primitive.ObjectID, coursePID primitive.ObjectID) (int, error) {
var err error
defer func() {
if err != nil {
logging.Errormf(logModReferenceMgmt, err.Error())
}
}()
studentCourseReferences, findErr := findStudentCourseRef(studentPID, coursePID)
if findErr != nil {
err = fmt.Errorf("[%s] - could not delete student-course reference DB entries due to query error", serverErrorMessages[seResourceNotFound])
return 0, err
}
var deleteCnt int64
for i := range studentCourseReferences {
_, deleteRecordErr := deleteCourseRecordByStudentPIDAndCoursePID(studentCourseReferences[i].StudentPID, studentCourseReferences[i].CoursePID)
if deleteRecordErr != nil {
err = fmt.Errorf("[%s] - stop deleting course-record reference (student PID %s course PID %s) since course record could not be deleted: %s",
serverErrorMessages[seCloudOpsError], studentCourseReferences[i].StudentPID, studentCourseReferences[i].CoursePID, deleteRecordErr.Error())
return int(deleteCnt), err
}
deleteFilter := bson.D{{"_id", studentCourseReferences[i].PID}}
deleteResult, err := dbPool.Collection(DBCollectionStudentCourseRef).DeleteMany(context.TODO(), deleteFilter)
if err != nil {
err = fmt.Errorf("[%s] - %s", serverErrorMessages[seDBResourceQuery], err.Error())
return 0, err
}
deleteCnt += deleteResult.DeletedCount
}
logging.Debugmf(logModReferenceMgmt, "Deleted %d student-course references from DB", deleteCnt)
return int(deleteCnt), nil
}