From 5a164f9369a584b9e1f85fb7b81b5cf568439fc7 Mon Sep 17 00:00:00 2001 From: lynnetteeee Date: Fri, 27 Sep 2024 23:19:34 +0800 Subject: [PATCH 01/11] Define Category model --- peer-prep-be/src/models/category_model.go | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 peer-prep-be/src/models/category_model.go diff --git a/peer-prep-be/src/models/category_model.go b/peer-prep-be/src/models/category_model.go new file mode 100644 index 0000000000..fc4eba7b0c --- /dev/null +++ b/peer-prep-be/src/models/category_model.go @@ -0,0 +1,8 @@ +package models + +import "go.mongodb.org/mongo-driver/bson/primitive" + +type Category struct { + Category_id primitive.ObjectID `json:"category_id,omitempty"` + Category_name string `json:"category_name" validate:"required"` +} From 6e82d89ff6f87af3a62f158d49cea587139dd177 Mon Sep 17 00:00:00 2001 From: lynnetteeee Date: Fri, 27 Sep 2024 23:19:56 +0800 Subject: [PATCH 02/11] Define endpoints --- peer-prep-be/src/routes/categories_route.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 peer-prep-be/src/routes/categories_route.go diff --git a/peer-prep-be/src/routes/categories_route.go b/peer-prep-be/src/routes/categories_route.go new file mode 100644 index 0000000000..7c516b3897 --- /dev/null +++ b/peer-prep-be/src/routes/categories_route.go @@ -0,0 +1,13 @@ +package routes + +import ( + "github.com/CS3219-AY2425S1/cs3219-ay2425s1-project-g01/peer-prep-be/src/controllers" + "github.com/labstack/echo/v4" +) + +func CategoriesRoute(e *echo.Echo) { + e.GET("/categories", controllers.GetCategories) + e.PUT("/categories/:categoryId", controllers.UpdateCategory) + e.POST("/categories", controllers.CreateCategory) + e.DELETE("/categories/:categoryId", controllers.DeleteCategory) +} From 6d74d1c3e6cffaa19c568c48753ab23f1d8187a7 Mon Sep 17 00:00:00 2001 From: lynnetteeee Date: Fri, 27 Sep 2024 23:20:11 +0800 Subject: [PATCH 03/11] Implement CRUD operations for categories --- peer-prep-be/src/controllers/categories.go | 165 +++++++++++++++++++++ peer-prep-be/src/server.go | 1 + 2 files changed, 166 insertions(+) create mode 100644 peer-prep-be/src/controllers/categories.go diff --git a/peer-prep-be/src/controllers/categories.go b/peer-prep-be/src/controllers/categories.go new file mode 100644 index 0000000000..319c88fb59 --- /dev/null +++ b/peer-prep-be/src/controllers/categories.go @@ -0,0 +1,165 @@ +package controllers + +import ( + "context" + "net/http" + "time" + + "github.com/CS3219-AY2425S1/cs3219-ay2425s1-project-g01/peer-prep-be/src/configs" + "github.com/CS3219-AY2425S1/cs3219-ay2425s1-project-g01/peer-prep-be/src/models" + "github.com/CS3219-AY2425S1/cs3219-ay2425s1-project-g01/peer-prep-be/src/responses" + "github.com/labstack/echo/v4" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +var categoriesCollection *mongo.Collection = configs.GetCollection(configs.DB, "categories") + +func GetCategories(c echo.Context) error { + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + cursor, err := categoriesCollection.Find(ctx, bson.M{}) + + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Message: err.Error(), + }) + } + + var categories []models.Category + if err = cursor.All(ctx, &categories); err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Message: err.Error(), + }) + } + + return c.JSON(http.StatusOK, responses.StatusResponse{ + Message: "Success", + Data: &echo.Map{"categories": categories}, + }) +} + +func CreateCategory(c echo.Context) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + // var existingCategory models.Category + var category models.Category + defer cancel() + + if err := c.Bind(&category); err != nil { + return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Message: err.Error(), + }) + } + + // Validate Category Name + if validationErr := validate.Struct(&category); validationErr != nil { + return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Status: http.StatusBadRequest, + Message: errMessage, + Data: &echo.Map{"data": validationErr.Error()}, + }) + } + + // Duplicate handling + // err := categoriesCollection.FindOne(ctx, bson.M{"categoryName": category.CategoryName}).Decode(&existingCategory) + // if err == nil { + // return c.JSON(http.StatusBadRequest, responses.StatusResponse{Message: "Category already exists"}) + // } + + newCategory := models.Category{ + Category_id: primitive.NewObjectID(), + Category_name: category.Category_name, + } + + // Insert new if it does not exist, case insensitive + _, err := categoriesCollection.UpdateOne(ctx, + bson.M{"category_name": newCategory.Category_name}, // Filter by category_name only, not the obj + bson.M{"$setOnInsert": bson.M{ + "category_id": newCategory.Category_id, + "category_name": newCategory.Category_name, + }}, + options.Update().SetUpsert(true).SetCollation(&options.Collation{ + Locale: "en", + Strength: 2, // Case-insensitive comparison + }), + ) + + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Message: err.Error(), + }) + } + + return c.JSON(http.StatusCreated, responses.StatusResponse{ + Message: "Category created successfully", + }) +} + +// Updates a category, e.g. singular -> plural +func UpdateCategory(c echo.Context) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + categoryId := c.Param("categoryId") + _, err := primitive.ObjectIDFromHex(categoryId) + if err != nil { + return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Message: "Invalid category ID: " + err.Error(), + }) + } + + var category models.Category + if err := c.Bind(&category); err != nil { + return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Message: err.Error(), + }) + } + + update := bson.M{ + "$set": bson.M{ + "category_name": category.Category_name, + }, + } + + // Perform the Update operation + _, err = categoriesCollection.UpdateOne(ctx, bson.M{"_id": categoryId}, update) + + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Message: err.Error(), + }) + } + + return c.JSON(http.StatusOK, responses.StatusResponse{ + Message: "Category updated successfully", + }) +} + +func DeleteCategory(c echo.Context) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + categoryId := c.Param("categoryId") + _, err := primitive.ObjectIDFromHex(categoryId) + if err != nil { + return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Message: "Invalid category ID: " + err.Error(), + }) + } + + _, err = categoriesCollection.DeleteOne(ctx, bson.M{"_id": categoryId}) + + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Message: err.Error(), + }) + } + + return c.JSON(http.StatusOK, responses.StatusResponse{ + Message: "Category deleted successfully", + }) +} diff --git a/peer-prep-be/src/server.go b/peer-prep-be/src/server.go index fa63022cec..931e0135d7 100644 --- a/peer-prep-be/src/server.go +++ b/peer-prep-be/src/server.go @@ -24,6 +24,7 @@ func main() { })) routes.QuestionRoute(e) + routes.CategoriesRoute(e) e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "Hello, World!") From d5069355c6e5365b083f6c9cb07f26c4f471da8c Mon Sep 17 00:00:00 2001 From: lynnetteeee Date: Fri, 27 Sep 2024 23:22:38 +0800 Subject: [PATCH 04/11] Add new endpoint in questions routes to get active categories Implement triggered category creation from adding/updating questions --- peer-prep-be/src/controllers/question.go | 57 +++++++++++++++++++++++ peer-prep-be/src/routes/question_route.go | 5 +- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/peer-prep-be/src/controllers/question.go b/peer-prep-be/src/controllers/question.go index 3093e747f8..57a81bdaa7 100644 --- a/peer-prep-be/src/controllers/question.go +++ b/peer-prep-be/src/controllers/question.go @@ -60,6 +60,16 @@ func CreateQuestion(c echo.Context) error { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) } + // Update categories collection + err = UpsertCategories(ctx, categoriesCollection, question.Question_categories) + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, + Message: "Error updating categories", + Data: &echo.Map{"data": err.Error()}, + }) + } + return c.JSON(http.StatusCreated, responses.StatusResponse{Status: http.StatusCreated, Message: successMessage, Data: &echo.Map{"data": result}}) } @@ -160,6 +170,16 @@ func UpdateQuestion(c echo.Context) error { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) } + // Update the categories collection only if a new category is added + err = UpsertCategories(ctx, categoriesCollection, question.Question_categories) + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, + Message: "Error updating categories", + Data: &echo.Map{"data": err.Error()}, + }) + } + return c.JSON(http.StatusOK, responses.StatusResponse{Status: http.StatusOK, Message: successMessage, Data: &echo.Map{"data": result}}) } @@ -272,3 +292,40 @@ func ProcessFilterParams(filterField string, filterValues string) bson.D { return filter } + +func GetDistinctQuestionCategories(c echo.Context) error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Get the distinct categories from the questions collection + categories, err := questionCollection.Distinct(ctx, "question_categories", bson.M{}) + if err != nil { + return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) + } + + return c.JSON(http.StatusOK, responses.StatusResponse{Status: http.StatusOK, Message: successMessage, Data: &echo.Map{"data": categories}}) +} + +func UpsertCategories(ctx context.Context, categoriesCollection *mongo.Collection, categoryNames []string) error { + for _, categoryName := range categoryNames { + // Insert or update category_name + newCategoryId := primitive.NewObjectID() + _, err := categoriesCollection.UpdateOne(ctx, + bson.M{"category_name": categoryName}, // Filter by category_name + bson.M{ + "$setOnInsert": bson.M{ + "category_id": newCategoryId, + "category_name": categoryName, + }, + }, + options.Update().SetUpsert(true).SetCollation(&options.Collation{ + Locale: "en", + Strength: 2, // Case-insensitive match + }), + ) + if err != nil { + return err + } + } + return nil +} diff --git a/peer-prep-be/src/routes/question_route.go b/peer-prep-be/src/routes/question_route.go index c091d96414..e2ca3690f2 100644 --- a/peer-prep-be/src/routes/question_route.go +++ b/peer-prep-be/src/routes/question_route.go @@ -7,9 +7,10 @@ import ( func QuestionRoute(e *echo.Echo) { e.GET("/questions/:questionId", controllers.GetQuestion) - e.GET("/questions", controllers.GetQuestions) + e.GET("/questions", controllers.GetQuestions) e.GET("/questions/search", controllers.SearchQuestion) e.POST("/question", controllers.CreateQuestion) e.PUT("/questions/:questionId", controllers.UpdateQuestion) e.DELETE("/questions/:questionId", controllers.DeleteQuestion) -} \ No newline at end of file + e.GET("/questionCategories", controllers.GetDistinctQuestionCategories) +} From bdaedf86adf4c94c87ef04917f72d6d14bb03a67 Mon Sep 17 00:00:00 2001 From: lynnetteeee Date: Sat, 28 Sep 2024 00:07:42 +0800 Subject: [PATCH 05/11] Update response for duplicate categories --- peer-prep-be/src/controllers/categories.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/peer-prep-be/src/controllers/categories.go b/peer-prep-be/src/controllers/categories.go index 319c88fb59..fab1a28acd 100644 --- a/peer-prep-be/src/controllers/categories.go +++ b/peer-prep-be/src/controllers/categories.go @@ -76,7 +76,7 @@ func CreateCategory(c echo.Context) error { } // Insert new if it does not exist, case insensitive - _, err := categoriesCollection.UpdateOne(ctx, + updateResult, err := categoriesCollection.UpdateOne(ctx, bson.M{"category_name": newCategory.Category_name}, // Filter by category_name only, not the obj bson.M{"$setOnInsert": bson.M{ "category_id": newCategory.Category_id, @@ -94,8 +94,16 @@ func CreateCategory(c echo.Context) error { }) } + // Check if a new category was created or if it was already existing + if updateResult.UpsertedCount > 0 { + // A new category was created + return c.JSON(http.StatusCreated, responses.StatusResponse{ + Message: "Category created successfully", + }) + } + return c.JSON(http.StatusCreated, responses.StatusResponse{ - Message: "Category created successfully", + Message: "Category already exists", }) } From 9db090bdc393e370753c8a7ad2772e39b59d8781 Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 10:10:58 +0800 Subject: [PATCH 06/11] Update route, status code for duplicate category --- peer-prep-be/src/controllers/categories.go | 2 +- peer-prep-be/src/routes/question_route.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/peer-prep-be/src/controllers/categories.go b/peer-prep-be/src/controllers/categories.go index fab1a28acd..e6f54f24e0 100644 --- a/peer-prep-be/src/controllers/categories.go +++ b/peer-prep-be/src/controllers/categories.go @@ -102,7 +102,7 @@ func CreateCategory(c echo.Context) error { }) } - return c.JSON(http.StatusCreated, responses.StatusResponse{ + return c.JSON(http.StatusConflict, responses.StatusResponse{ Message: "Category already exists", }) } diff --git a/peer-prep-be/src/routes/question_route.go b/peer-prep-be/src/routes/question_route.go index e2ca3690f2..aa832b6fff 100644 --- a/peer-prep-be/src/routes/question_route.go +++ b/peer-prep-be/src/routes/question_route.go @@ -12,5 +12,5 @@ func QuestionRoute(e *echo.Echo) { e.POST("/question", controllers.CreateQuestion) e.PUT("/questions/:questionId", controllers.UpdateQuestion) e.DELETE("/questions/:questionId", controllers.DeleteQuestion) - e.GET("/questionCategories", controllers.GetDistinctQuestionCategories) + e.GET("/questions/categories", controllers.GetDistinctQuestionCategories) } From 4f79a6be89400c8a4823fd3a34e9b07eb57faa2a Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 14:23:54 +0800 Subject: [PATCH 07/11] Update statuses --- peer-prep-be/src/controllers/categories.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/peer-prep-be/src/controllers/categories.go b/peer-prep-be/src/controllers/categories.go index e6f54f24e0..07db0b9060 100644 --- a/peer-prep-be/src/controllers/categories.go +++ b/peer-prep-be/src/controllers/categories.go @@ -26,6 +26,7 @@ func GetCategories(c echo.Context) error { if err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, Message: err.Error(), }) } @@ -33,11 +34,13 @@ func GetCategories(c echo.Context) error { var categories []models.Category if err = cursor.All(ctx, &categories); err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, Message: err.Error(), }) } return c.JSON(http.StatusOK, responses.StatusResponse{ + Status: http.StatusOK, Message: "Success", Data: &echo.Map{"categories": categories}, }) @@ -51,6 +54,7 @@ func CreateCategory(c echo.Context) error { if err := c.Bind(&category); err != nil { return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Status: http.StatusBadRequest, Message: err.Error(), }) } @@ -90,6 +94,7 @@ func CreateCategory(c echo.Context) error { if err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, Message: err.Error(), }) } @@ -98,11 +103,13 @@ func CreateCategory(c echo.Context) error { if updateResult.UpsertedCount > 0 { // A new category was created return c.JSON(http.StatusCreated, responses.StatusResponse{ + Status: http.StatusCreated, Message: "Category created successfully", }) } return c.JSON(http.StatusConflict, responses.StatusResponse{ + Status: http.StatusConflict, Message: "Category already exists", }) } @@ -116,6 +123,7 @@ func UpdateCategory(c echo.Context) error { _, err := primitive.ObjectIDFromHex(categoryId) if err != nil { return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Status: http.StatusBadRequest, Message: "Invalid category ID: " + err.Error(), }) } @@ -123,6 +131,7 @@ func UpdateCategory(c echo.Context) error { var category models.Category if err := c.Bind(&category); err != nil { return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Status: http.StatusBadRequest, Message: err.Error(), }) } @@ -138,11 +147,13 @@ func UpdateCategory(c echo.Context) error { if err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, Message: err.Error(), }) } return c.JSON(http.StatusOK, responses.StatusResponse{ + Status: http.StatusOK, Message: "Category updated successfully", }) } @@ -155,6 +166,7 @@ func DeleteCategory(c echo.Context) error { _, err := primitive.ObjectIDFromHex(categoryId) if err != nil { return c.JSON(http.StatusBadRequest, responses.StatusResponse{ + Status: http.StatusBadRequest, Message: "Invalid category ID: " + err.Error(), }) } @@ -163,11 +175,13 @@ func DeleteCategory(c echo.Context) error { if err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ + Status: http.StatusInternalServerError, Message: err.Error(), }) } return c.JSON(http.StatusOK, responses.StatusResponse{ + Status: http.StatusOK, Message: "Category deleted successfully", }) } From 4408e60ba1925dd0d0f4517b473b72dc8b41eb2e Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 14:35:26 +0800 Subject: [PATCH 08/11] Remove UpsertCategories, fixed bug where wrong objectId of question returned in response --- peer-prep-be/src/controllers/question.go | 49 ++---------------------- 1 file changed, 4 insertions(+), 45 deletions(-) diff --git a/peer-prep-be/src/controllers/question.go b/peer-prep-be/src/controllers/question.go index 57a81bdaa7..1b3e773817 100644 --- a/peer-prep-be/src/controllers/question.go +++ b/peer-prep-be/src/controllers/question.go @@ -46,8 +46,10 @@ func CreateQuestion(c echo.Context) error { return c.JSON(http.StatusBadRequest, responses.StatusResponse{Status: http.StatusBadRequest, Message: errMessage, Data: &echo.Map{"data": "Question with the same title already exists."}}) } + new_question_id := primitive.NewObjectID() + newQuestion := models.Question{ - Question_id: primitive.NewObjectID(), + Question_id: new_question_id, Question_title: question.Question_title, Question_description: question.Question_description, Question_categories: question.Question_categories, @@ -60,16 +62,7 @@ func CreateQuestion(c echo.Context) error { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) } - // Update categories collection - err = UpsertCategories(ctx, categoriesCollection, question.Question_categories) - if err != nil { - return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ - Status: http.StatusInternalServerError, - Message: "Error updating categories", - Data: &echo.Map{"data": err.Error()}, - }) - } - + result.InsertedID = new_question_id return c.JSON(http.StatusCreated, responses.StatusResponse{Status: http.StatusCreated, Message: successMessage, Data: &echo.Map{"data": result}}) } @@ -170,16 +163,6 @@ func UpdateQuestion(c echo.Context) error { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) } - // Update the categories collection only if a new category is added - err = UpsertCategories(ctx, categoriesCollection, question.Question_categories) - if err != nil { - return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ - Status: http.StatusInternalServerError, - Message: "Error updating categories", - Data: &echo.Map{"data": err.Error()}, - }) - } - return c.JSON(http.StatusOK, responses.StatusResponse{Status: http.StatusOK, Message: successMessage, Data: &echo.Map{"data": result}}) } @@ -305,27 +288,3 @@ func GetDistinctQuestionCategories(c echo.Context) error { return c.JSON(http.StatusOK, responses.StatusResponse{Status: http.StatusOK, Message: successMessage, Data: &echo.Map{"data": categories}}) } - -func UpsertCategories(ctx context.Context, categoriesCollection *mongo.Collection, categoryNames []string) error { - for _, categoryName := range categoryNames { - // Insert or update category_name - newCategoryId := primitive.NewObjectID() - _, err := categoriesCollection.UpdateOne(ctx, - bson.M{"category_name": categoryName}, // Filter by category_name - bson.M{ - "$setOnInsert": bson.M{ - "category_id": newCategoryId, - "category_name": categoryName, - }, - }, - options.Update().SetUpsert(true).SetCollation(&options.Collation{ - Locale: "en", - Strength: 2, // Case-insensitive match - }), - ) - if err != nil { - return err - } - } - return nil -} From 129e2aa0d587c756fe2f0284b86bd4a84dd0ea2e Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 14:35:53 +0800 Subject: [PATCH 09/11] Update question.go --- peer-prep-be/src/controllers/question.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/peer-prep-be/src/controllers/question.go b/peer-prep-be/src/controllers/question.go index 1b3e773817..c8951b4ec6 100644 --- a/peer-prep-be/src/controllers/question.go +++ b/peer-prep-be/src/controllers/question.go @@ -46,10 +46,10 @@ func CreateQuestion(c echo.Context) error { return c.JSON(http.StatusBadRequest, responses.StatusResponse{Status: http.StatusBadRequest, Message: errMessage, Data: &echo.Map{"data": "Question with the same title already exists."}}) } - new_question_id := primitive.NewObjectID() + newQuestionId := primitive.NewObjectID() newQuestion := models.Question{ - Question_id: new_question_id, + Question_id: newQuestionId, Question_title: question.Question_title, Question_description: question.Question_description, Question_categories: question.Question_categories, @@ -62,7 +62,7 @@ func CreateQuestion(c echo.Context) error { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{Status: http.StatusInternalServerError, Message: errMessage, Data: &echo.Map{"data": err.Error()}}) } - result.InsertedID = new_question_id + result.InsertedID = newQuestionId return c.JSON(http.StatusCreated, responses.StatusResponse{Status: http.StatusCreated, Message: successMessage, Data: &echo.Map{"data": result}}) } From 5ed48520e68b984208fc466cafb35546bd8fd5be Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 14:38:03 +0800 Subject: [PATCH 10/11] Reordered code segments --- peer-prep-be/src/controllers/question.go | 96 ++++++++++++------------ 1 file changed, 49 insertions(+), 47 deletions(-) diff --git a/peer-prep-be/src/controllers/question.go b/peer-prep-be/src/controllers/question.go index c8951b4ec6..51770a06a9 100644 --- a/peer-prep-be/src/controllers/question.go +++ b/peer-prep-be/src/controllers/question.go @@ -23,6 +23,55 @@ var validate = validator.New() var errMessage = "error" var successMessage = "success" +// Helper Functions +// Takes in the sortField and sortOrder from the query string and returns the FindOptions object +func ProcessSortParams(sortField string, sortOrder string) *options.FindOptions { + var findOptions *options.FindOptions + + if sortField != "" { + order := 1 // Default to ascending order + if sortOrder == "desc" { + order = -1 // If 'desc' is provided, sort in descending order + } + + // Set the sorting options + findOptions = options.Find().SetCollation(&options.Collation{Locale: "en_US"}).SetSort(bson.D{{Key: sortField, Value: order}}) + } else { + // No sorting specified, natural MongoDB order + findOptions = options.Find() + } + + return findOptions +} + +func ProcessFilterParams(filterField string, filterValues string) bson.D { + filter := bson.D{{}} + + if filterField != "" && filterValues != "" { + values := strings.Split(filterValues, ",") + + if len(values) == 1 { + filter = bson.D{{Key: filterField, Value: values[0]}} + } else { + filterConditions := bson.A{} + for _, value := range values { + filterConditions = append(filterConditions, bson.D{{Key: filterField, Value: value}}) + } + + filter = bson.D{ + { + Key: "$or", + Value: filterConditions, + }, + } + } + + } + + return filter +} + +// Services func CreateQuestion(c echo.Context) error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) var existingQuestion models.Question @@ -229,53 +278,6 @@ func SearchQuestion(c echo.Context) error { return c.JSON(http.StatusOK, responses.StatusResponse{Status: http.StatusOK, Message: successMessage, Data: &echo.Map{"data": questions}}) } -// Takes in the sortField and sortOrder from the query string and returns the FindOptions object -func ProcessSortParams(sortField string, sortOrder string) *options.FindOptions { - var findOptions *options.FindOptions - - if sortField != "" { - order := 1 // Default to ascending order - if sortOrder == "desc" { - order = -1 // If 'desc' is provided, sort in descending order - } - - // Set the sorting options - findOptions = options.Find().SetCollation(&options.Collation{Locale: "en_US"}).SetSort(bson.D{{Key: sortField, Value: order}}) - } else { - // No sorting specified, natural MongoDB order - findOptions = options.Find() - } - - return findOptions -} - -func ProcessFilterParams(filterField string, filterValues string) bson.D { - filter := bson.D{{}} - - if filterField != "" && filterValues != "" { - values := strings.Split(filterValues, ",") - - if len(values) == 1 { - filter = bson.D{{Key: filterField, Value: values[0]}} - } else { - filterConditions := bson.A{} - for _, value := range values { - filterConditions = append(filterConditions, bson.D{{Key: filterField, Value: value}}) - } - - filter = bson.D{ - { - Key: "$or", - Value: filterConditions, - }, - } - } - - } - - return filter -} - func GetDistinctQuestionCategories(c echo.Context) error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() From cb175f4afb1883235e994b5a41183ba06f1764e3 Mon Sep 17 00:00:00 2001 From: Kervyn <73232587+kervyntan@users.noreply.github.com> Date: Sat, 28 Sep 2024 14:42:13 +0800 Subject: [PATCH 11/11] Update categories.go --- peer-prep-be/src/controllers/categories.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/peer-prep-be/src/controllers/categories.go b/peer-prep-be/src/controllers/categories.go index 07db0b9060..60731081f4 100644 --- a/peer-prep-be/src/controllers/categories.go +++ b/peer-prep-be/src/controllers/categories.go @@ -74,8 +74,10 @@ func CreateCategory(c echo.Context) error { // return c.JSON(http.StatusBadRequest, responses.StatusResponse{Message: "Category already exists"}) // } + newCategoryId := primitive.NewObjectID() + newCategory := models.Category{ - Category_id: primitive.NewObjectID(), + Category_id: newCategoryId, Category_name: category.Category_name, } @@ -98,6 +100,8 @@ func CreateCategory(c echo.Context) error { Message: err.Error(), }) } + + updateResult.UpsertedID = newCategoryId; // Check if a new category was created or if it was already existing if updateResult.UpsertedCount > 0 { @@ -105,6 +109,7 @@ func CreateCategory(c echo.Context) error { return c.JSON(http.StatusCreated, responses.StatusResponse{ Status: http.StatusCreated, Message: "Category created successfully", + Data: &echo.Map{"data": updateResult}, }) } @@ -143,7 +148,7 @@ func UpdateCategory(c echo.Context) error { } // Perform the Update operation - _, err = categoriesCollection.UpdateOne(ctx, bson.M{"_id": categoryId}, update) + updateResult, err := categoriesCollection.UpdateOne(ctx, bson.M{"_id": categoryId}, update) if err != nil { return c.JSON(http.StatusInternalServerError, responses.StatusResponse{ @@ -155,6 +160,7 @@ func UpdateCategory(c echo.Context) error { return c.JSON(http.StatusOK, responses.StatusResponse{ Status: http.StatusOK, Message: "Category updated successfully", + Data: &echo.Map{"data": updateResult}, }) }