Blog/Comment/comment.go

106 lines
2.6 KiB
Go

package Comment
import (
"github.com/nspcc-dev/neo-go/pkg/interop/native/oracle"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
)
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: "none",
authorId: authorId,
postId: postId,
text: text,
likes: 0,
dislikes: 0,
}
storeURL := "https://www.uuidgenerator.net/api/version7"
oracle.Request(storeURL, nil, "cbGetUUID", nil, oracle.MinimumResponseGas)
newComment.id = storage.Get(ctx, "lastCommentId").(string)
comments := GetByPostId(postId)
comments = append(comments, newComment)
storage.Put(ctx, postId+"_comment", std.Serialize(comments))
}
func cbGetUUID(url string, commentData any, code int, result []byte) {
callingHash := runtime.GetCallingScriptHash()
if !callingHash.Equals(oracle.Hash) {
panic("not called from the oracle contract")
}
if code != oracle.Success {
panic("request failed for " + url + " with code " + std.Itoa(code, 10))
}
runtime.Log("result for " + url + " is: " + string(result))
runtime.Log("Last Comment id is: " + string(result))
ctx := storage.GetContext()
storage.Put(ctx, "lastCommentId", string(result))
}
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))
}