feat: comment contract
This commit is contained in:
parent
9f162e5363
commit
1a2161fbb2
1 changed files with 77 additions and 2 deletions
|
@ -1,8 +1,83 @@
|
|||
package Comments
|
||||
package Comment
|
||||
|
||||
type Comments struct {
|
||||
import (
|
||||
"github.com/nspcc-dev/neo-go/pkg/interop/native/std"
|
||||
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
|
||||
"github.com/rs/xid"
|
||||
)
|
||||
|
||||
type Comment struct {
|
||||
id string
|
||||
authorId string
|
||||
postId string
|
||||
text string
|
||||
likes int
|
||||
dislikes int
|
||||
}
|
||||
|
||||
func CreateNewComment(authorId string, postId string, text string) {
|
||||
ctx := storage.GetContext()
|
||||
newComment := Comment{
|
||||
id: xid.New().String(),
|
||||
authorId: authorId,
|
||||
postId: postId,
|
||||
text: text,
|
||||
likes: 0,
|
||||
dislikes: 0,
|
||||
}
|
||||
|
||||
comments := GetByPostId(postId)
|
||||
comments = append(comments, newComment)
|
||||
storage.Put(ctx, postId+"_comment", std.Serialize(comments))
|
||||
}
|
||||
|
||||
func GetByPostId(postId string) []Comment {
|
||||
ctx := storage.GetContext()
|
||||
return std.Deserialize(storage.Get(ctx, postId+"_comment").([]byte)).([]Comment)
|
||||
}
|
||||
|
||||
func GetByAuthorId(postId string, authorId string) []Comment {
|
||||
comments := GetByPostId(postId)
|
||||
var commentsByAuthor []Comment
|
||||
for _, comment := range comments {
|
||||
if comment.authorId == authorId {
|
||||
commentsByAuthor = append(commentsByAuthor, comment)
|
||||
}
|
||||
}
|
||||
|
||||
return commentsByAuthor
|
||||
}
|
||||
|
||||
func GetComment(commentId string, postId string) Comment {
|
||||
comments := GetByPostId(postId)
|
||||
for _, comment := range comments {
|
||||
if comment.id == commentId {
|
||||
return comment
|
||||
}
|
||||
}
|
||||
|
||||
panic("Коммента с таким айдишником нету")
|
||||
}
|
||||
|
||||
func RateComment(isLike bool, postId string, commentId string) {
|
||||
comment := GetComment(commentId, postId)
|
||||
if isLike {
|
||||
comment.likes++
|
||||
} else {
|
||||
comment.dislikes++
|
||||
}
|
||||
|
||||
UpdateComment(comment, postId)
|
||||
}
|
||||
|
||||
func UpdateComment(comment Comment, postId string) {
|
||||
ctx := storage.GetContext()
|
||||
comments := GetByPostId(postId)
|
||||
for i := 0; i < len(comments); i++ {
|
||||
if comments[i].id == comment.id {
|
||||
comments[i] = comment
|
||||
}
|
||||
}
|
||||
|
||||
storage.Put(ctx, postId+"_comment", std.Serialize(comments))
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue