Skip to content

Commit

Permalink
adding complete/incomplete request endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
ddusichka committed Oct 9, 2023
1 parent f8ca960 commit a046d20
Show file tree
Hide file tree
Showing 5 changed files with 202 additions and 0 deletions.
2 changes: 2 additions & 0 deletions api/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
Expand Down
19 changes: 19 additions & 0 deletions api/src/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func (pg *PgController) Serve() *gin.Engine {
}
c.JSON(http.StatusOK, gift)
})

r.GET("/gifts", func(c *gin.Context) {
gifts, err := pg.AllExampleGifts()
if err != nil {
Expand All @@ -39,6 +40,24 @@ func (pg *PgController) Serve() *gin.Engine {
c.JSON(http.StatusOK, gifts)
})

// Get incomplete gift requests
r.GET("/requests/incomplete", func(c *gin.Context) {
gifts, err := pg.IncompleteRequests()
if err != nil {
c.JSON(http.StatusInternalServerError, "Oops")
}
c.JSON(http.StatusOK, gifts)
})

// Get complete gift requests
r.GET("/requests/complete", func(c *gin.Context) {
gifts, err := pg.CompleteRequests()
if err != nil {
c.JSON(http.StatusInternalServerError, "Oops")
}
c.JSON(http.StatusOK, gifts)
})

r.POST("/addGift", func(c *gin.Context) {
var input model.ExampleGiftInput
fmt.Print(c)
Expand Down
20 changes: 20 additions & 0 deletions api/src/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ type Model interface {
GetExampleGift(int64) ExampleGift
AllExampleGifts() ([]ExampleGift, error)
AddExampleGift(ExampleGiftInput) (ExampleGift, error)
IncompleteRequests() ([]GiftRequest, error)
CompleteRequests() ([]GiftRequest, error)
}

func (m *PgModel) GetExampleGift(id int64) ExampleGift {
Expand Down Expand Up @@ -43,3 +45,21 @@ func (m *PgModel) AllExampleGifts() ([]ExampleGift, error) {
}
return gifts, nil
}

func (m *PgModel) IncompleteRequests() ([]GiftRequest, error) {
gifts, err := GetIncompleteGiftRequestsFromDB(m.Conn)

if err != nil {
return []GiftRequest{}, err
}
return gifts, nil
}

func (m *PgModel) CompleteRequests() ([]GiftRequest, error) {
gifts, err := GetCompleteGiftRequestsFromDB(m.Conn)

if err != nil {
return []GiftRequest{}, err
}
return gifts, nil
}
16 changes: 16 additions & 0 deletions api/src/model/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,20 @@ func GetAllExampleGiftsFromDB(db *gorm.DB) ([]ExampleGift, error) {
return nil, err
}
return gifts, nil
}

func GetIncompleteGiftRequestsFromDB(db *gorm.DB) ([]GiftRequest, error) {
var requests []GiftRequest
if err := db.Where("gift_response_id IS NULL").Find(&requests).Error; err != nil {
return nil, err
}
return requests, nil
}

func GetCompleteGiftRequestsFromDB(db *gorm.DB) ([]GiftRequest, error) {
var requests []GiftRequest
if err := db.Where("gift_response_id IS NOT NULL").Find(&requests).Error; err != nil {
return nil, err
}
return requests, nil
}
145 changes: 145 additions & 0 deletions api/tests/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import (
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"sort"
"time"

"github.com/lib/pq"

"os"
"testing"

Expand Down Expand Up @@ -133,5 +136,147 @@ func TestGetExampleGift(t *testing.T) {
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))
}


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 {
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.GiftRequest{})
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()
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(),
}

// Create the GiftRequest and call the endpoint
err = db.Create(&request).Error
assert.NoError(t, err)
req1, err := http.NewRequest("GET", fmt.Sprintf("/requests/incomplete"), nil)
router.ServeHTTP(w, req1)

assert.Equal(t, 200, w.Code)

var requestsRetrieved []model.GiftRequest
if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil {
t.Fatalf("Error unmarshaling JSON: %v", e)
}

// 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) {
// 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.GiftRequest{})
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()

// 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
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(),
}

// Create the GiftRequest and call the endpoint
err = db.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 requestsRetrieved []model.GiftRequest
if e := json.Unmarshal(w.Body.Bytes(), &requestsRetrieved); e != nil {
t.Fatalf("Error unmarshaling JSON: %v", e)
}

// 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.DateNeeded.In(time.UTC).Round(time.Millisecond),
requestsRetrieved[0].DateNeeded.In(time.UTC).Round(time.Millisecond))
}

0 comments on commit a046d20

Please sign in to comment.