Skip to content
This repository has been archived by the owner on Mar 3, 2022. It is now read-only.

Commit

Permalink
Merge pull request #10 from sameersbn/fix-9
Browse files Browse the repository at this point in the history
no-op if item is already starred by the user
  • Loading branch information
prydonius authored Oct 27, 2017
2 parents b1b2243 + 62da993 commit e05037e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
22 changes: 16 additions & 6 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,7 @@ func GetStars(w http.ResponseWriter, req *http.Request) {
for _, it := range items {
it.StargazersCount = len(it.StargazersIDs)
if currentUser, err := getCurrentUserID(req); err == nil {
for _, id := range it.StargazersIDs {
if id == currentUser {
it.HasStarred = true
break
}
}
it.HasStarred = hasStarred(it, currentUser)
}
}
response.NewDataResponse(items).Write(w)
Expand Down Expand Up @@ -114,6 +109,11 @@ func UpdateStar(w http.ResponseWriter, req *http.Request) {
// Otherwise we just need to update the database
op := "$pull"
if params.HasStarred {
// no-op if item is already starred by user
if hasStarred(&it, uid) {
response.NewDataResponse(it).WithCode(http.StatusOK).Write(w)
return
}
op = "$push"
}

Expand Down Expand Up @@ -168,3 +168,13 @@ var getCurrentUserID = func(req *http.Request) (bson.ObjectId, error) {
}
return "", errors.New("invalid token")
}

// hasStarred returns true if item is starred by the user
func hasStarred(it *item, user bson.ObjectId) bool {
for _, id := range it.StargazersIDs {
if id == user {
return true
}
}
return false
}
19 changes: 19 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,25 @@ func TestUpdateStar(t *testing.T) {
}
}

func TestUpdateStarDoesNotDuplicate(t *testing.T) {
var m mock.Mock
currentUser := bson.NewObjectId()
m.On("One", &item{}).Return(nil).Run(func(args mock.Arguments) {
*args.Get(0).(*item) = item{ID: "stable/wordpress", StargazersIDs: []bson.ObjectId{currentUser}}
})
dbSession = testutil.NewMockSession(&m)
oldGetCurrentUserID := getCurrentUserID
getCurrentUserID = func(_ *http.Request) (bson.ObjectId, error) { return currentUser, nil }
defer func() { getCurrentUserID = oldGetCurrentUserID }()

m.AssertNotCalled(t, "UpdateId")
w := httptest.NewRecorder()
requestBody := `{"id": "stable/wordpress", "has_starred": true}`
req := httptest.NewRequest("PUT", "/v1/stars", bytes.NewBuffer([]byte(requestBody)))
UpdateStar(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}

func TestUpdateStarInsertsInexistantItem(t *testing.T) {
var m mock.Mock
m.On("One", &item{}).Return(errors.New("not found"))
Expand Down

0 comments on commit e05037e

Please sign in to comment.