move vote setter to service level

This commit is contained in:
Umputun
2019-04-07 14:05:19 -05:00
parent 446cb486a0
commit 2e4dfe3891
4 changed files with 19 additions and 15 deletions
+5 -14
View File
@@ -312,28 +312,19 @@ func (s *Rest) alterComments(comments []store.Comment, r *http.Request) (res []s
// prepare vote info for client view
vote := func(c store.Comment, r *http.Request) store.Comment {
c.Vote = 0 //default is "none" (not voted)
user, err := rest.GetUserInfo(r)
_, err := rest.GetUserInfo(r)
if err != nil {
c.Votes = nil // hide voters list }()
c.Vote = 0 //default is "none" (not voted) for non-authed user
c.Votes = nil // hide voters list
return c
}
if v, ok := c.Votes[user.ID]; ok {
if v {
c.Vote = 1
} else {
c.Vote = -1
}
}
c.Votes = nil // hide voters list }()
c.Votes = nil // hide voters list
return c
}
for i, c := range res {
c = vote(c, r)
c = vote(c, r) // hide voters list
res[i] = c
}
+1 -1
View File
@@ -18,7 +18,7 @@ type Comment struct {
Locator Locator `json:"locator"`
Score int `json:"score"`
Votes map[string]bool `json:"votes,omitempty"`
Vote int `json:"vote"` // vote for the current user, -1/1/0. set by rest from Votes
Vote int `json:"vote"` // vote for the current user, -1/1/0.
Controversy float64 `json:"controversy,omitempty"`
Timestamp time.Time `json:"time" bson:"time"`
Edit *Edit `json:"edit,omitempty" bson:"edit,omitempty"` // pointer to have empty default in json response
+9
View File
@@ -206,6 +206,15 @@ func (s *DataStore) Vote(locator store.Locator, commentID string, userID string,
comment.Score--
}
comment.Vote = 0
if v, ok := comment.Votes[userID]; ok {
if v {
comment.Vote = 1
} else {
comment.Vote = -1
}
}
comment.Controversy = s.controversy(s.upsAndDowns(comment))
return comment, s.Put(locator, comment)
@@ -179,11 +179,13 @@ func TestService_Vote(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, 3, len(res))
assert.Equal(t, 0, res[0].Score)
assert.Equal(t, 0, res[0].Vote)
assert.Equal(t, map[string]bool(nil), res[0].Votes, "no votes initially")
c, err := b.Vote(store.Locator{URL: "https://radio-t.com", SiteID: "radio-t"}, res[0].ID, "user1", true)
assert.Nil(t, err)
assert.Equal(t, 1, c.Score)
assert.Equal(t, 1, c.Vote)
assert.Equal(t, map[string]bool{"user1": true}, c.Votes, "user voted +")
c, err = b.Vote(store.Locator{URL: "https://radio-t.com", SiteID: "radio-t"}, res[0].ID, "user", true)
@@ -197,6 +199,7 @@ func TestService_Vote(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, 3, len(res))
assert.Equal(t, 1, res[0].Score)
assert.Equal(t, 1, res[0].Vote)
assert.Equal(t, 0.0, res[0].Controversy)
_, err = b.Vote(store.Locator{URL: "https://radio-t.com", SiteID: "radio-t"}, res[0].ID, "user1", false)
@@ -205,6 +208,7 @@ func TestService_Vote(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, 3, len(res))
assert.Equal(t, 0, res[0].Score)
assert.Equal(t, 0, res[0].Vote)
assert.Equal(t, map[string]bool(nil), res[0].Votes, "vote reset ok")
}