diff --git a/api/src/controller/controller.go b/api/src/controller/controller.go index 312beb7..c3b65fb 100644 --- a/api/src/controller/controller.go +++ b/api/src/controller/controller.go @@ -3,11 +3,9 @@ package controller import ( "CaitsCurates/backend/src/model" "fmt" - "net/http" - "strconv" - "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" + "net/http" ) type Controller interface { @@ -22,24 +20,6 @@ func (pg *PgController) Serve() *gin.Engine { r := gin.Default() r.Use(cors.Default()) - r.GET("/gifts/:id", func(c *gin.Context) { - id := c.Param("id") - intId, err := strconv.Atoi(id) - gift := pg.GetExampleGift(int64(intId)) - if err != nil { - panic(err) - } - c.JSON(http.StatusOK, gift) - }) - - r.GET("/gifts", func(c *gin.Context) { - gifts, err := pg.AllExampleGifts() - if err != nil { - c.JSON(http.StatusInternalServerError, "Oops") - } - c.JSON(http.StatusOK, gifts) - }) - // Get incomplete gift requests r.GET("/requests/incomplete", func(c *gin.Context) { gifts, err := pg.IncompleteRequests() @@ -58,24 +38,57 @@ func (pg *PgController) Serve() *gin.Engine { c.JSON(http.StatusOK, gifts) }) - r.POST("/addGift", func(c *gin.Context) { - var input model.ExampleGiftInput - fmt.Print(c) + r.POST("/addGiftResponse", func(c *gin.Context) { + var input model.GiftResponse + if err := c.BindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, "Failed to unmarshal respone") + + fmt.Print(err) + + return + } + insertedResponse, err := pg.AddResponse(input) + + if err != nil { + c.JSON(http.StatusBadRequest, input) + panic(err) + } + + c.JSON(http.StatusOK, insertedResponse) + }) + r.POST("/addGiftRequest", func(c *gin.Context) { + var input model.GiftRequest + if err := c.BindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, "Failed to unmarshal request") + fmt.Print(err) + return + } + insertedRequest, err := pg.AddRequest(input) + + if err != nil { + c.JSON(http.StatusBadRequest, input) + panic(err) + } + + c.JSON(http.StatusOK, insertedRequest) + }) + r.POST("/addGiftCollection", func(c *gin.Context) { + var input model.GiftCollection if err := c.BindJSON(&input); err != nil { - c.JSON(http.StatusBadRequest, "Failed to unmarshal gift") + c.JSON(http.StatusBadRequest, "Failed to unmarshal collection") fmt.Print(err) return } - insertedGift, err := pg.AddExampleGift(input) + insertedCollection, err := pg.AddCollection(input) if err != nil { c.JSON(http.StatusBadRequest, input) panic(err) } - c.JSON(http.StatusOK, insertedGift) + c.JSON(http.StatusOK, insertedCollection) }) return r diff --git a/api/src/main.go b/api/src/main.go index 13609f5..3fdc5e0 100644 --- a/api/src/main.go +++ b/api/src/main.go @@ -34,8 +34,15 @@ func main() { os.Exit(1) } // Auto migrate tables - err = db.AutoMigrate(&model.ExampleGift{}) - + err = db.AutoMigrate(model.User{}, model.Customer{}, model.GiftRequest{}, model.GiftCollection{}, model.GiftResponse{}, model.Admin{}) + user := model.User{} + err = db.Create(&user).Error + var retrievedUser model.User + err = db.First(&retrievedUser).Error + customer := model.Customer{ + User: retrievedUser, + } + err = db.Create(&customer).Error // Check for errors if err != nil { fmt.Println("Error auto-migrating:", err) diff --git a/api/src/model/model.go b/api/src/model/model.go index b7b546c..53f097f 100644 --- a/api/src/model/model.go +++ b/api/src/model/model.go @@ -9,41 +9,42 @@ type PgModel struct { } type Model interface { - GetExampleGift(int64) ExampleGift - AllExampleGifts() ([]ExampleGift, error) - AddExampleGift(ExampleGiftInput) (ExampleGift, error) + AddRequest(GiftRequest) (GiftRequest, error) + AddResponse(GiftResponse) (GiftResponse, error) + AddCollection(GiftCollection) (GiftCollection, error) IncompleteRequests() ([]GiftRequest, error) CompleteRequests() ([]GiftRequest, error) } -func (m *PgModel) GetExampleGift(id int64) ExampleGift { - gift, err := GetExampleGiftFromDB(m.Conn, id) +func (m *PgModel) AddRequest(inputRequest GiftRequest) (GiftRequest, error) { + + createdRequest, err := WriteRequestToDb(m.Conn, inputRequest) if err != nil { - panic(err) + return GiftRequest{}, err } - return gift + return createdRequest, nil } +func (m *PgModel) AddResponse(inputResponse GiftResponse) (GiftResponse, error) { -func (m *PgModel) AddExampleGift(inputGift ExampleGiftInput) (ExampleGift, error) { - - createdGift, err := WriteExampleGiftToDb(m.Conn, inputGift) + createdResponse, err := WriteResponseToDb(m.Conn, inputResponse) if err != nil { - return ExampleGift{}, err + return GiftResponse{}, err } - return createdGift, nil + return createdResponse, nil } +func (m *PgModel) AddCollection(inputCollection GiftCollection) (GiftCollection, error) { -func (m *PgModel) AllExampleGifts() ([]ExampleGift, error) { - gifts, err := GetAllExampleGiftsFromDB(m.Conn) + createdCollection, err := WriteCollectionToDb(m.Conn, inputCollection) if err != nil { - return []ExampleGift{}, err + return GiftCollection{}, err } - return gifts, nil + + return createdCollection, nil } func (m *PgModel) IncompleteRequests() ([]GiftRequest, error) { diff --git a/api/src/model/transactions.go b/api/src/model/transactions.go index 81f3671..127a58a 100644 --- a/api/src/model/transactions.go +++ b/api/src/model/transactions.go @@ -4,31 +4,23 @@ import ( "gorm.io/gorm" ) -// WriteExampleGiftToDb saves the ExampleGift and returns it -func WriteExampleGiftToDb(db *gorm.DB, inputGift ExampleGiftInput) (ExampleGift, error) { - eg := ExampleGift{Name: inputGift.Name, Price: inputGift.Price} - if err := db.Create(&eg).Error; err != nil { - return ExampleGift{}, err +func WriteRequestToDb(db *gorm.DB, inputRequest GiftRequest) (GiftRequest, error) { + if err := db.Create(&inputRequest).Error; err != nil { + return GiftRequest{}, err } - return eg, nil + return inputRequest, nil } - -// GetExampleGiftFromDB fetches an ExampleGift by ID -func GetExampleGiftFromDB(db *gorm.DB, id int64) (ExampleGift, error) { - var eg ExampleGift - if err := db.Where("id = ?", id).First(&eg).Error; err != nil { - return ExampleGift{}, err +func WriteResponseToDb(db *gorm.DB, inputResponse GiftResponse) (GiftResponse, error) { + if err := db.Create(&inputResponse).Error; err != nil { + return GiftResponse{}, err } - return eg, nil + return inputResponse, nil } - -// GetAllExampleGiftsFromDB fetches all ExampleGift -func GetAllExampleGiftsFromDB(db *gorm.DB) ([]ExampleGift, error) { - var gifts []ExampleGift - if err := db.Find(&gifts).Error; err != nil { - return nil, err +func WriteCollectionToDb(db *gorm.DB, inputCollection GiftCollection) (GiftCollection, error) { + if err := db.Create(&inputCollection).Error; err != nil { + return GiftCollection{}, err } - return gifts, nil + return inputCollection, nil } func GetIncompleteGiftRequestsFromDB(db *gorm.DB) ([]GiftRequest, error) { @@ -45,4 +37,4 @@ func GetCompleteGiftRequestsFromDB(db *gorm.DB) ([]GiftRequest, error) { return nil, err } return requests, nil -} \ No newline at end of file +} diff --git a/api/src/model/types.go b/api/src/model/types.go index 24097e6..c203c05 100644 --- a/api/src/model/types.go +++ b/api/src/model/types.go @@ -6,17 +6,6 @@ import ( "time" ) -type ExampleGift struct { - gorm.Model - Name string - Price int -} - -type ExampleGiftInput struct { - Name string - Price int -} - type Gift struct { gorm.Model Name string @@ -37,7 +26,7 @@ type GiftRequest struct { RecipientInterests pq.StringArray `gorm:"type:text[]"` BudgetMax uint BudgetMin uint - GiftResponse GiftResponse + GiftResponse *GiftResponse DateNeeded time.Time } diff --git a/api/tests/api_test.go b/api/tests/api_test.go index 2ff88a6..b901349 100644 --- a/api/tests/api_test.go +++ b/api/tests/api_test.go @@ -22,7 +22,7 @@ import ( "gorm.io/gorm" ) -func TestAddExampleGift(t *testing.T) { +func TestGetIncompleteGiftRequests(t *testing.T) { // Database setup dsn := "user=testuser password=testpwd host=localhost port=5433 dbname=testdb sslmode=disable" if dbURL, exists := os.LookupEnv("TEST_DATABASE_URL"); exists { @@ -32,8 +32,9 @@ func TestAddExampleGift(t *testing.T) { if err != nil { t.Fatalf("Unable to connect to database: %v", err) } + // Put auto migrations here - err = db.AutoMigrate(&model.ExampleGift{}) + err = db.AutoMigrate(&model.GiftRequest{}, &model.Customer{}, &model.User{}, &model.GiftResponse{}) if err != nil { panic("failed to migrate test database schema") } @@ -47,50 +48,62 @@ func TestAddExampleGift(t *testing.T) { router := c.Serve() // Test code + w := httptest.NewRecorder() - w1 := httptest.NewRecorder() - testGift := model.ExampleGiftInput{ - Name: "nice sweater", - Price: 50, + user := model.User{} + err = tx.Create(&user).Error + assert.NoError(t, err) + var retrievedUser model.User + err = tx.First(&retrievedUser).Error + assert.NoError(t, err) + customer := model.Customer{ + User: retrievedUser, } - giftJson, err := json.Marshal(testGift) - if err != nil { - t.Fatalf("Error marshaling JSON: %v", err) + err = tx.Create(&customer).Error + assert.NoError(t, err) + var retrievedCustomer model.Customer + err = tx.First(&retrievedCustomer).Error + request := model.GiftRequest{ + CustomerID: retrievedCustomer.ID, + RecipientName: "Friend", + RecipientAge: 25, + Occasion: pq.StringArray{"Birthday", "Anniversary"}, + RecipientInterests: pq.StringArray{"Reading", "Gaming"}, + BudgetMax: 50, + BudgetMin: 15, + DateNeeded: time.Now(), } - req, err := http.NewRequest("POST", "/addGift", bytes.NewBuffer(giftJson)) - if err != nil { - t.Fatalf("Error creating request: %v", err) - } + // Create the GiftRequest and call the endpoint + err = tx.Create(&request).Error + assert.NoError(t, err) + req1, err := http.NewRequest("GET", fmt.Sprintf("/requests/incomplete"), nil) + router.ServeHTTP(w, req1) - router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) - var giftAdded model.ExampleGift - if e := json.Unmarshal(w.Body.Bytes(), &giftAdded); e != nil { + var requestsRetrieved []model.GiftRequest + if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil { t.Fatalf("Error unmarshaling JSON: %v", e) } - assert.Equal(t, testGift.Price, giftAdded.Price) - req1, err := http.NewRequest("GET", fmt.Sprintf("/gifts/%d", giftAdded.ID), nil) - router.ServeHTTP(w1, req1) - assert.Equal(t, 200, w1.Code) - - var giftRetrieved model.ExampleGift - var giftRetrievedDB model.ExampleGift - if e := json.Unmarshal(w1.Body.Bytes(), &giftRetrieved); e != nil { - t.Fatalf("Error unmarshaling JSON: %v", e) - } - err = tx.First(&giftRetrievedDB, giftRetrievedDB.ID).Error + // Choose only the most recently created incomplete request (the one we just added) + sort.Slice(requestsRetrieved, func(i, j int) bool { + return requestsRetrieved[i].CreatedAt.After(requestsRetrieved[j].CreatedAt) + }) - assert.Equal(t, giftAdded.ID, giftRetrieved.ID) - assert.Equal(t, giftAdded.Name, giftRetrieved.Name) - assert.Equal(t, giftAdded.Price, giftRetrieved.Price) - assert.Equal(t, giftAdded.CreatedAt.In(time.UTC).Round(time.Millisecond), - giftRetrieved.CreatedAt.In(time.UTC).Round(time.Millisecond)) + assert.Equal(t, request.ID, requestsRetrieved[0].ID) + assert.Equal(t, request.RecipientName, requestsRetrieved[0].RecipientName) + assert.Equal(t, request.RecipientAge, requestsRetrieved[0].RecipientAge) + assert.Equal(t, request.Occasion, requestsRetrieved[0].Occasion) + assert.Equal(t, request.RecipientInterests, requestsRetrieved[0].RecipientInterests) + assert.Equal(t, request.BudgetMax, requestsRetrieved[0].BudgetMax) + assert.Equal(t, request.BudgetMin, requestsRetrieved[0].BudgetMin) + assert.Nil(t, request.GiftResponseID) // make sure it's actually incomplete! + assert.Equal(t, request.DateNeeded.In(time.UTC).Round(time.Millisecond), + requestsRetrieved[0].DateNeeded.In(time.UTC).Round(time.Millisecond)) } - -func TestGetExampleGift(t *testing.T) { +func TestGetCompleteGiftRequests(t *testing.T) { // Database setup dsn := "user=testuser password=testpwd host=localhost port=5433 dbname=testdb sslmode=disable" if dbURL, exists := os.LookupEnv("TEST_DATABASE_URL"); exists { @@ -101,7 +114,7 @@ func TestGetExampleGift(t *testing.T) { t.Fatalf("Unable to connect to database: %v", err) } // Put auto migrations here - err = db.AutoMigrate(&model.ExampleGift{}) + err = db.AutoMigrate(&model.GiftRequest{}, &model.Customer{}, &model.User{}, &model.GiftResponse{}) if err != nil { panic("failed to migrate test database schema") } @@ -116,31 +129,74 @@ func TestGetExampleGift(t *testing.T) { // Test code w := httptest.NewRecorder() - gift := model.ExampleGift{ - Name: "nice sweater", - Price: 50, + + // Create GiftResponse + giftResponse := model.GiftResponse{CustomMessage: "This is a custom message", GiftCollection: model.GiftCollection{CollectionName: "Name"}} + err = tx.Create(&giftResponse).Error + assert.NoError(t, err) + // Create GiftRequest + user := model.User{} + err = tx.Create(&user).Error + assert.NoError(t, err) + var retrievedUser model.User + err = tx.First(&retrievedUser).Error + assert.NoError(t, err) + customer := model.Customer{ + User: retrievedUser, } - err = db.Create(&gift).Error + err = tx.Create(&customer).Error assert.NoError(t, err) - req1, err := http.NewRequest("GET", fmt.Sprintf("/gifts/%d", gift.ID), nil) + var retrievedCustomer model.Customer + err = tx.First(&retrievedCustomer).Error + request := model.GiftRequest{ + CustomerID: retrievedCustomer.ID, + GiftResponse: &giftResponse, + RecipientName: "Friend", + RecipientAge: 25, + Occasion: pq.StringArray{"Birthday", "Anniversary"}, + RecipientInterests: pq.StringArray{"Reading", "Gaming"}, + BudgetMax: 50, + BudgetMin: 15, + DateNeeded: time.Now(), + } + + // Create the GiftRequest and call the endpoint + err = tx.Create(&request).Error + + assert.NoError(t, err) + req1, err := http.NewRequest("GET", fmt.Sprintf("/requests/complete"), nil) router.ServeHTTP(w, req1) assert.Equal(t, 200, w.Code) - var giftRetrieved model.ExampleGift - if e := json.Unmarshal(w.Body.Bytes(), &giftRetrieved); e != nil { + var requestsRetrieved []model.GiftRequest + if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil { t.Fatalf("Error unmarshaling JSON: %v", e) } - assert.Equal(t, gift.ID, giftRetrieved.ID) - assert.Equal(t, gift.Name, giftRetrieved.Name) - assert.Equal(t, gift.Price, giftRetrieved.Price) - assert.Equal(t, gift.CreatedAt.In(time.UTC).Round(time.Millisecond), - giftRetrieved.CreatedAt.In(time.UTC).Round(time.Millisecond)) -} + // Choose only the most recently created incomplete request (the one we just added) + sort.Slice(requestsRetrieved, func(i, j int) bool { + return requestsRetrieved[i].CreatedAt.After(requestsRetrieved[j].CreatedAt) + }) + assert.Equal(t, request.ID, requestsRetrieved[0].ID) + assert.Equal(t, request.RecipientName, requestsRetrieved[0].RecipientName) + assert.Equal(t, request.RecipientAge, requestsRetrieved[0].RecipientAge) + assert.Equal(t, request.Occasion, requestsRetrieved[0].Occasion) + assert.Equal(t, request.RecipientInterests, requestsRetrieved[0].RecipientInterests) + assert.Equal(t, request.BudgetMax, requestsRetrieved[0].BudgetMax) + assert.Equal(t, request.BudgetMin, requestsRetrieved[0].BudgetMin) + assert.Equal(t, request.GiftResponseID, requestsRetrieved[0].GiftResponseID) + assert.Equal(t, request.GiftResponse.ID, giftResponse.ID) + assert.NotNil(t, request.GiftResponse) // make sure preloading works + assert.Equal(t, request.GiftResponse.GiftCollectionID, giftResponse.GiftCollectionID) + assert.Equal(t, request.GiftResponse.GiftCollection, giftResponse.GiftCollection) + assert.Equal(t, request.GiftResponse.CustomMessage, giftResponse.CustomMessage) + assert.Equal(t, request.DateNeeded.In(time.UTC).Round(time.Millisecond), + requestsRetrieved[0].DateNeeded.In(time.UTC).Round(time.Millisecond)) +} -func TestGetIncompleteGiftRequests(t *testing.T) { +func TestAddRequest(t *testing.T) { // Database setup dsn := "user=testuser password=testpwd host=localhost port=5433 dbname=testdb sslmode=disable" if dbURL, exists := os.LookupEnv("TEST_DATABASE_URL"); exists { @@ -151,7 +207,7 @@ func TestGetIncompleteGiftRequests(t *testing.T) { t.Fatalf("Unable to connect to database: %v", err) } // Put auto migrations here - err = db.AutoMigrate(&model.GiftRequest{}) + err = db.AutoMigrate(&model.GiftRequest{}, &model.Customer{}, &model.User{}, &model.GiftResponse{}) if err != nil { panic("failed to migrate test database schema") } @@ -166,48 +222,49 @@ func TestGetIncompleteGiftRequests(t *testing.T) { // Test code w := httptest.NewRecorder() + + // Create GiftResponse + assert.NoError(t, err) + // Create GiftRequest + user := model.User{} + err = tx.Create(&user).Error + assert.NoError(t, err) + var retrievedUser model.User + err = tx.First(&retrievedUser).Error + assert.NoError(t, err) + customer := model.Customer{ + User: retrievedUser, + } + err = tx.Create(&customer).Error + assert.NoError(t, err) + var retrievedCustomer model.Customer + err = tx.First(&retrievedCustomer).Error request := model.GiftRequest{ - CustomerID: 1, - RecipientName: "Friend", - RecipientAge: 25, - Occasion: pq.StringArray{"Birthday", "Anniversary"}, - RecipientInterests: pq.StringArray{"Reading", "Gaming"}, - BudgetMax: 50, - BudgetMin: 15, - // GiftResponse: leaving this out to signify an incomplete request - DateNeeded: time.Now(), + CustomerID: retrievedCustomer.ID, + RecipientName: "Friend", } // Create the GiftRequest and call the endpoint - err = db.Create(&request).Error + requestJSON, err := json.Marshal(request) + if err != nil { + t.Fatalf("Error marshaling JSON: %v", err) + } assert.NoError(t, err) - req1, err := http.NewRequest("GET", fmt.Sprintf("/requests/incomplete"), nil) + req1, err := http.NewRequest("POST", fmt.Sprintf("/addGiftRequest"), bytes.NewBuffer(requestJSON)) router.ServeHTTP(w, req1) - assert.Equal(t, 200, w.Code) - var requestsRetrieved []model.GiftRequest - if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil { + var addedRequest model.GiftRequest + if e := json.Unmarshal(w.Body.Bytes(), &addedRequest); e != nil { t.Fatalf("Error unmarshaling JSON: %v", e) } + var retrievedRequest model.GiftRequest + err = tx.First(&retrievedRequest).Error + assert.Equal(t, addedRequest.RecipientName, retrievedRequest.RecipientName) - // Choose only the most recently created incomplete request (the one we just added) - sort.Slice(requestsRetrieved, func(i, j int) bool { - return requestsRetrieved[i].CreatedAt.After(requestsRetrieved[j].CreatedAt) - }) - - assert.Equal(t, request.ID, requestsRetrieved[0].ID) - assert.Equal(t, request.RecipientName, requestsRetrieved[0].RecipientName) - assert.Equal(t, request.RecipientAge, requestsRetrieved[0].RecipientAge) - assert.Equal(t, request.Occasion, requestsRetrieved[0].Occasion) - assert.Equal(t, request.RecipientInterests, requestsRetrieved[0].RecipientInterests) - assert.Equal(t, request.BudgetMax, requestsRetrieved[0].BudgetMax) - assert.Equal(t, request.BudgetMin, requestsRetrieved[0].BudgetMin) - assert.Nil(t, request.GiftResponseID) // make sure it's actually incomplete! - assert.Equal(t, request.DateNeeded.In(time.UTC).Round(time.Millisecond), - requestsRetrieved[0].DateNeeded.In(time.UTC).Round(time.Millisecond)) } -func TestGetCompleteGiftRequests(t *testing.T) { + +func TestAddResponse(t *testing.T) { // Database setup dsn := "user=testuser password=testpwd host=localhost port=5433 dbname=testdb sslmode=disable" if dbURL, exists := os.LookupEnv("TEST_DATABASE_URL"); exists { @@ -218,13 +275,13 @@ func TestGetCompleteGiftRequests(t *testing.T) { t.Fatalf("Unable to connect to database: %v", err) } // Put auto migrations here - err = db.AutoMigrate(&model.GiftRequest{}) + err = db.AutoMigrate(&model.GiftRequest{}, &model.Customer{}, &model.User{}, &model.GiftResponse{}, &model.GiftCollection{}) if err != nil { panic("failed to migrate test database schema") } // Wrap the DB connection in a transaction tx := db.Begin() - defer tx.Rollback() + //defer tx.Rollback() // Create Model and Controller m := &model.PgModel{Conn: tx} @@ -235,54 +292,109 @@ func TestGetCompleteGiftRequests(t *testing.T) { w := httptest.NewRecorder() // Create GiftResponse - giftResponse := model.GiftResponse{CustomMessage: "This is a custom message", GiftCollection: model.GiftCollection{CollectionName: "Name"}} - err = db.Create(&giftResponse).Error assert.NoError(t, err) - // Create GiftRequest + user := model.User{} + err = tx.Create(&user).Error + assert.NoError(t, err) + var retrievedUser model.User + err = tx.First(&retrievedUser).Error + assert.NoError(t, err) + customer := model.Customer{ + User: retrievedUser, + } + err = tx.Create(&customer).Error + assert.NoError(t, err) + var retrievedCustomer model.Customer + err = tx.First(&retrievedCustomer).Error request := model.GiftRequest{ - CustomerID: 1, - RecipientName: "Friend", - RecipientAge: 25, - Occasion: pq.StringArray{"Birthday", "Anniversary"}, - RecipientInterests: pq.StringArray{"Reading", "Gaming"}, - BudgetMax: 50, - BudgetMin: 15, - GiftResponse: giftResponse, - DateNeeded: time.Now(), + CustomerID: retrievedCustomer.ID, + RecipientName: "Friend", } - - // Create the GiftRequest and call the endpoint - err = db.Create(&request).Error + err = tx.Create(&request).Error assert.NoError(t, err) - req1, err := http.NewRequest("GET", fmt.Sprintf("/requests/complete"), nil) + collection := model.GiftCollection{ + CollectionName: "collection", + } + err = tx.Create(&collection).Error + assert.NoError(t, err) + response := model.GiftResponse{ + GiftCollection: collection, + CustomMessage: "Message", + } + responseJSON, err := json.Marshal(response) + if err != nil { + t.Fatalf("Error marshaling JSON: %v", err) + } + assert.NoError(t, err) + req1, err := http.NewRequest("POST", fmt.Sprintf("/addGiftResponse"), bytes.NewBuffer(responseJSON)) router.ServeHTTP(w, req1) - assert.Equal(t, 200, w.Code) - var requestsRetrieved []model.GiftRequest - if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil { + var addedResponse model.GiftResponse + if e := json.Unmarshal(w.Body.Bytes(), &addedResponse); e != nil { t.Fatalf("Error unmarshaling JSON: %v", e) } + var retrievedResponse model.GiftResponse + err = tx.Preload("GiftCollection").First(&retrievedResponse, "id = ?", addedResponse.ID).Error + assert.NoError(t, err) + assert.Equal(t, retrievedResponse.GiftCollectionID, addedResponse.GiftCollectionID) + assert.Equal(t, retrievedResponse.GiftCollection.CollectionName, addedResponse.GiftCollection.CollectionName) + assert.Equal(t, retrievedResponse.CustomMessage, addedResponse.CustomMessage) - // Choose only the most recently created incomplete request (the one we just added) - sort.Slice(requestsRetrieved, func(i, j int) bool { - return requestsRetrieved[i].CreatedAt.After(requestsRetrieved[j].CreatedAt) - }) +} - assert.Equal(t, request.ID, requestsRetrieved[0].ID) - assert.Equal(t, request.RecipientName, requestsRetrieved[0].RecipientName) - assert.Equal(t, request.RecipientAge, requestsRetrieved[0].RecipientAge) - assert.Equal(t, request.Occasion, requestsRetrieved[0].Occasion) - assert.Equal(t, request.RecipientInterests, requestsRetrieved[0].RecipientInterests) - assert.Equal(t, request.BudgetMax, requestsRetrieved[0].BudgetMax) - assert.Equal(t, request.BudgetMin, requestsRetrieved[0].BudgetMin) - assert.Equal(t, request.GiftResponseID, requestsRetrieved[0].GiftResponseID) - assert.Equal(t, request.GiftResponse.ID, giftResponse.ID) - assert.NotNil(t, request.GiftResponse) // make sure preloading works - assert.Equal(t, request.GiftResponse.GiftCollectionID, giftResponse.GiftCollectionID) - assert.Equal(t, request.GiftResponse.GiftCollection, giftResponse.GiftCollection) - assert.Equal(t, request.GiftResponse.CustomMessage, giftResponse.CustomMessage) - assert.Equal(t, request.DateNeeded.In(time.UTC).Round(time.Millisecond), - requestsRetrieved[0].DateNeeded.In(time.UTC).Round(time.Millisecond)) -} \ No newline at end of file +func TestAddCollection(t *testing.T) { + // Database setup + dsn := "user=testuser password=testpwd host=localhost port=5433 dbname=testdb sslmode=disable" + if dbURL, exists := os.LookupEnv("TEST_DATABASE_URL"); exists { + dsn = dbURL + } + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) + if err != nil { + t.Fatalf("Unable to connect to database: %v", err) + } + // Put auto migrations here + err = db.AutoMigrate(&model.GiftCollection{}, &model.Gift{}) + if err != nil { + panic("failed to migrate test database schema") + } + // Wrap the DB connection in a transaction + tx := db.Begin() + //defer tx.Rollback() + + // Create Model and Controller + m := &model.PgModel{Conn: tx} + c := &c.PgController{Model: m} + router := c.Serve() + + // Test code + w := httptest.NewRecorder() + + gift := model.Gift{ + Name: "Gift1", + } + collection := model.GiftCollection{ + Gifts: []*model.Gift{&gift}, + CollectionName: "collection", + } + + collectionJSON, err := json.Marshal(collection) + if err != nil { + t.Fatalf("Error marshaling JSON: %v", err) + } + assert.NoError(t, err) + req1, err := http.NewRequest("POST", fmt.Sprintf("/addGiftCollection"), bytes.NewBuffer(collectionJSON)) + router.ServeHTTP(w, req1) + assert.Equal(t, 200, w.Code) + + var addedCollection model.GiftCollection + if e := json.Unmarshal(w.Body.Bytes(), &addedCollection); e != nil { + t.Fatalf("Error unmarshaling JSON: %v", e) + } + var retrievedCollection model.GiftCollection + err = tx.Preload("Gifts").First(&retrievedCollection, "id = ?", addedCollection.ID).Error + assert.NoError(t, err) + assert.Equal(t, retrievedCollection.CollectionName, addedCollection.CollectionName) + assert.Equal(t, retrievedCollection.Gifts[0].Name, addedCollection.Gifts[0].Name) +} diff --git a/api/tests/db_test.go b/api/tests/db_test.go index 8cb0d44..5719ba9 100644 --- a/api/tests/db_test.go +++ b/api/tests/db_test.go @@ -117,7 +117,7 @@ func TestGiftRequestModel(t *testing.T) { assert.NoError(t, err) // Create GiftRequest - giftRequest := model.GiftRequest{GiftResponse: giftResponse} + giftRequest := model.GiftRequest{GiftResponse: &giftResponse} user := model.User{Email: "tsai.me@northeastern.edu", FirstName: "Joey", LastName: "Tsai", Password: "dgeeg32"} customer := model.Customer{GiftRequests: []*model.GiftRequest{&giftRequest}, User: user} err = tx.Create(&customer).Error diff --git a/client/package-lock.json b/client/package-lock.json index 3b1ca3b..ee0617d 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -1366,6 +1366,20 @@ "dev": true, "license": "ISC" }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/function-bind": { "version": "1.1.1", "dev": true, @@ -1938,7 +1952,9 @@ } }, "node_modules/postcss": { - "version": "8.4.29", + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", "dev": true, "funding": [ { @@ -1954,7 +1970,6 @@ "url": "https://github.com/sponsors/ai" } ], - "license": "MIT", "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0",