You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB

4 years ago
package story
import (
"database/sql"
"fmt"
"net/http"
"time"
"github.com/imdotdev/im.dev/server/pkg/db"
"github.com/imdotdev/im.dev/server/pkg/e"
)
4 years ago
func Like(storyID string, userId string) *e.Error {
4 years ago
exist := Exist(storyID)
if !exist {
return e.New(http.StatusNotFound, e.NotFound)
}
tbl := getStorySqlTable(storyID)
// 查询当前like状态
liked := GetLiked(storyID, userId)
if liked {
// 已经喜欢过该篇文章,更改为不喜欢
4 years ago
_, err := db.Conn.Exec("DELETE FROM likes WHERE story_id=? and user_id=?", storyID, userId)
4 years ago
if err != nil {
return e.New(http.StatusInternalServerError, e.Internal)
}
db.Conn.Exec(fmt.Sprintf("UPDATE %s SET likes=likes-1 WHERE id=?", tbl), storyID)
} else {
4 years ago
_, err := db.Conn.Exec("INSERT INTO likes (story_id,user_id,created) VALUES (?,?,?)", storyID, userId, time.Now())
4 years ago
if err != nil {
logger.Warn("add like error", "error", err)
return e.New(http.StatusInternalServerError, e.Internal)
}
db.Conn.Exec(fmt.Sprintf("UPDATE %s SET likes=likes+1 WHERE id=?", tbl), storyID)
}
return nil
}
4 years ago
func GetLiked(storyID string, userID string) bool {
4 years ago
liked := false
var nid string
4 years ago
err := db.Conn.QueryRow("SELECT story_id FROM likes WHERE story_id=? and user_id=?", storyID, userID).Scan(&nid)
4 years ago
if err != nil && err != sql.ErrNoRows {
logger.Warn("query story like error", "error", err)
return false
}
if nid == storyID {
liked = true
}
return liked
}