322 lines
13 KiB
Go
322 lines
13 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/doug-martin/goqu/v9"
|
|
"github.com/graphql-go/graphql"
|
|
"github.com/thoas/go-funk"
|
|
)
|
|
|
|
type Game struct {
|
|
ID int `json:"id" gorm:"primaryKey"`
|
|
Title string `json:"title"`
|
|
Era string `json:"era"`
|
|
Style string `json:"style"`
|
|
Device string `json:"device"`
|
|
Orientation string `json:"orientation"`
|
|
Tags string `json:"tags"`
|
|
Rank string `json:"rank"`
|
|
UserId int `json:"user_id"`
|
|
Content string `json:"content"`
|
|
CategoryID int `json:"category_id"`
|
|
Image string `json:"image"`
|
|
Images string `json:"images"`
|
|
User User `json:"user" gorm:"foreignKey:UserId"`
|
|
Collect bool `json:"collect" gorm:"column:is_collect"`
|
|
Praise bool `json:"praise" gorm:"column:is_praise"`
|
|
CollectCount int `json:"collect_count" gorm:"column:collect_num"`
|
|
PraiseCount int `json:"praise_count" gorm:"column:praise"`
|
|
CommentCount int `json:"comment_count" gorm:"column:comment_num"`
|
|
ImageCount int `json:"image_count" gorm:"column:total_image_count"`
|
|
TextCount int `json:"text_count" gorm:"column:text_count"`
|
|
TextList []string `json:"text_list" gorm:"-"`
|
|
CreateTime time.Time `json:"create_time"`
|
|
UpdateTime time.Time `json:"update_time"`
|
|
Emoji1 int `json:"emoji1"`
|
|
Emoji2 int `json:"emoji2"`
|
|
Emoji3 int `json:"emoji3"`
|
|
Emoji4 int `json:"emoji4"`
|
|
Emoji5 int `json:"emoji5"`
|
|
Views int `json:"views"`
|
|
}
|
|
|
|
func (Game) TableName() string {
|
|
return "web_article"
|
|
}
|
|
|
|
var gameType = graphql.NewObject(graphql.ObjectConfig{
|
|
Name: "Game",
|
|
Description: "游戏",
|
|
Fields: graphql.Fields{
|
|
"id": &graphql.Field{Type: graphql.Int, Description: "游戏ID"},
|
|
"title": &graphql.Field{Type: graphql.String, Description: "游戏标题"},
|
|
"era": &graphql.Field{Type: graphql.String, Description: "游戏上线年份"},
|
|
"tags": &graphql.Field{Type: graphql.String, Description: "游戏标签"},
|
|
"rank": &graphql.Field{Type: graphql.String, Description: "游戏精选"},
|
|
"style": &graphql.Field{Type: graphql.String, Description: "游戏风格"},
|
|
"device": &graphql.Field{Type: graphql.String, Description: "游戏平台"},
|
|
"orientation": &graphql.Field{Type: graphql.String, Description: "屏幕方向"},
|
|
"category_id": &graphql.Field{Type: graphql.Int, Description: "分类ID"},
|
|
"user": &graphql.Field{Type: userType, Description: "所属用户"},
|
|
"create_time": &graphql.Field{Type: graphql.DateTime, Description: "游戏创建时间"},
|
|
"update_time": &graphql.Field{Type: graphql.DateTime, Description: "游戏更新时间"},
|
|
"praise": &graphql.Field{Type: graphql.Boolean, Description: "当前用户是否点赞"},
|
|
"collect": &graphql.Field{Type: graphql.Boolean, Description: "当前用户是否收藏"},
|
|
"praise_count": &graphql.Field{Type: graphql.Int, Description: "点赞数"},
|
|
"collect_count": &graphql.Field{Type: graphql.Int, Description: "收藏数"},
|
|
"image_count": &graphql.Field{Type: graphql.Int, Description: "图片数"},
|
|
"text_count": &graphql.Field{Type: graphql.Int, Description: "文字数量"},
|
|
"text_list": &graphql.Field{Type: graphql.NewList(graphql.String), Description: "文字列表"},
|
|
"emoji1": &graphql.Field{Type: graphql.Int, Description: "表情1数量"},
|
|
"emoji2": &graphql.Field{Type: graphql.Int, Description: "表情2数量"},
|
|
"emoji3": &graphql.Field{Type: graphql.Int, Description: "表情3数量"},
|
|
"emoji4": &graphql.Field{Type: graphql.Int, Description: "表情4数量"},
|
|
"emoji5": &graphql.Field{Type: graphql.Int, Description: "表情5数量"},
|
|
"views": &graphql.Field{Type: graphql.Int, Description: "浏览量"},
|
|
},
|
|
})
|
|
|
|
var GameItems = &graphql.Field{
|
|
Name: "games",
|
|
Description: "游戏列表",
|
|
Type: graphql.NewObject(graphql.ObjectConfig{
|
|
Name: "GameConnection",
|
|
Description: "条件筛选游戏列表",
|
|
Fields: graphql.Fields{
|
|
"list": &graphql.Field{Type: graphql.NewList(gameType), Description: "游戏列表"},
|
|
"total": &graphql.Field{Type: graphql.Int, Description: "游戏总数"},
|
|
},
|
|
}),
|
|
Args: graphql.FieldConfigArgument{
|
|
"collect": &graphql.ArgumentConfig{Type: graphql.Int, Description: "按指定用户收藏筛选"},
|
|
"praise": &graphql.ArgumentConfig{Type: graphql.Int, Description: "按指定用户点赞筛选"},
|
|
"era": &graphql.ArgumentConfig{Type: graphql.String, Description: "按年份筛选游戏"},
|
|
"tags": &graphql.ArgumentConfig{Type: graphql.String, Description: "按标签筛选游戏"},
|
|
"style": &graphql.ArgumentConfig{Type: graphql.String, Description: "按风格筛选游戏"},
|
|
"device": &graphql.ArgumentConfig{Type: graphql.String, Description: "按平台筛选游戏"},
|
|
"orientation": &graphql.ArgumentConfig{Type: graphql.String, Description: "按屏幕方向筛选游戏"},
|
|
"category_id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "按分类ID筛选游戏"},
|
|
"user_id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "按用户ID筛选游戏"},
|
|
"id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "筛选游戏中指定ID的"},
|
|
"title": &graphql.ArgumentConfig{Type: graphql.String, Description: "筛选游戏中含有指定标题的"},
|
|
"rank": &graphql.ArgumentConfig{Type: graphql.String, Description: "筛选游戏中含有指定排名的"},
|
|
"create_time": &graphql.ArgumentConfig{Type: graphql.DateTime, Description: "按创建时间筛选游戏"},
|
|
"update_time": &graphql.ArgumentConfig{Type: graphql.DateTime, Description: "按修改时间筛选游戏"},
|
|
"sort": &graphql.ArgumentConfig{Type: graphql.String, Description: "按指定字段排序游戏", DefaultValue: "id"},
|
|
"order": &graphql.ArgumentConfig{Type: orderType, Description: "排序类型(升序或降序)", DefaultValue: "ASC"},
|
|
"first": &graphql.ArgumentConfig{Type: graphql.Int, Description: "翻页参数(傳回清單中的前n個元素)"},
|
|
"last": &graphql.ArgumentConfig{Type: graphql.Int, Description: "翻页参数(傳回清單中的最後n個元素)"},
|
|
"after": &graphql.ArgumentConfig{Type: graphql.Int, Description: "翻页参数(傳回清單中指定遊標之後的元素)"},
|
|
"before": &graphql.ArgumentConfig{Type: graphql.Int, Description: "翻页参数(傳回清單中指定遊標之前的元素)"},
|
|
},
|
|
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
var games []Game
|
|
var total int
|
|
var err error
|
|
|
|
// 游戏的顶级ID为 22
|
|
var query = goqu.Dialect("mysql").From("web_article").Where(goqu.Ex{"category_top_id": 22})
|
|
|
|
// 筛选条件
|
|
for _, format := range []string{"id", "title", "style", "device", "orientation", "era", "category_id", "tags", "rank"} {
|
|
if p.Args[format] != nil {
|
|
query = query.Where(goqu.C(format).Eq(p.Args[format]))
|
|
}
|
|
}
|
|
|
|
// 按指定用户点赞筛选
|
|
if p.Args["praise"] != nil {
|
|
query = query.Join(goqu.T("web_praise"), goqu.On(
|
|
goqu.I("web_article.id").Eq(goqu.I("web_praise.praise_id")),
|
|
goqu.I("web_praise.user_id").Eq(p.Args["praise"]),
|
|
goqu.I("web_praise.type").Eq(0),
|
|
))
|
|
}
|
|
|
|
// 按指定用户收藏筛选
|
|
if p.Args["collect"] != nil {
|
|
query = query.Join(goqu.T("web_collect"), goqu.On(
|
|
goqu.I("web_article.id").Eq(goqu.I("web_collect.collect_id")),
|
|
goqu.I("web_collect.user_id").Eq(p.Args["collect"]),
|
|
goqu.I("web_collect.type").Eq(0),
|
|
))
|
|
}
|
|
|
|
// 如果查询了 total 字段
|
|
if existField(p.Info.FieldASTs[0].SelectionSet.Selections, "total") {
|
|
sql, _, _ := query.ToSQL()
|
|
sql = strings.Replace(sql, "SELECT *", "SELECT COUNT(*)", 1)
|
|
if err := db.Raw(sql).Scan(&total).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
// 如果没有外部排序则使用指定排序(正则sort只能是字母数字下划下)
|
|
if p.Args["text"] == nil && p.Args["similar"] == nil && p.Args["interest"] == nil {
|
|
sort := regexp.MustCompile(`[^a-zA-Z0-9_]`).ReplaceAllString(p.Args["sort"].(string), "")
|
|
query = query.Select("web_article.id", goqu.L(
|
|
fmt.Sprintf("ROW_NUMBER() OVER(ORDER BY web_article.%s %s)", sort, p.Args["order"]),
|
|
).As("row_num"))
|
|
} else {
|
|
// 排序条件
|
|
if p.Args["sort"] != nil {
|
|
if p.Args["order"].(string) == "ASC" {
|
|
query = query.Order(goqu.C(p.Args["sort"].(string)).Asc())
|
|
}
|
|
if p.Args["order"].(string) == "DESC" {
|
|
query = query.Order(goqu.C(p.Args["sort"].(string)).Desc())
|
|
}
|
|
}
|
|
}
|
|
|
|
// 取所有数据的前N条
|
|
sql, _, _ := query.ToSQL()
|
|
|
|
// 遊標截取篩選結果集的前N条
|
|
var cursor string
|
|
if p.Args["after"] != nil {
|
|
cursor = fmt.Sprintf(`WHERE row_num > (SELECT row_num FROM RankedArticles WHERE RankedArticles.id = %d)`, p.Args["after"].(int))
|
|
}
|
|
|
|
var limit int = 10
|
|
if p.Args["first"] != nil {
|
|
limit = p.Args["first"].(int)
|
|
} else if p.Args["last"] != nil {
|
|
limit = p.Args["last"].(int)
|
|
}
|
|
|
|
// 字段选择
|
|
var user_id = p.Context.Value("user_id").(int)
|
|
var fields = ListItem(p.Info.FieldASTs[0].SelectionSet.Selections)
|
|
var praise, collect, text_count string
|
|
if funk.Contains(fields, "praise") {
|
|
praise = fmt.Sprintf(",CASE WHEN EXISTS (SELECT 1 FROM web_praise WHERE web_praise.praise_id = web_article.id AND web_praise.user_id = %d AND web_praise.type = 0) THEN TRUE ELSE FALSE END AS is_praise", user_id)
|
|
}
|
|
if funk.Contains(fields, "collect") {
|
|
collect = fmt.Sprintf(",CASE WHEN EXISTS (SELECT 1 FROM web_collect WHERE web_collect.collect_id = web_article.id AND web_collect.user_id = %d AND web_collect.type = 0) THEN TRUE ELSE FALSE END AS is_collect", user_id)
|
|
}
|
|
|
|
sql = fmt.Sprintf(`
|
|
WITH RankedArticles AS (%s)
|
|
SELECT web_article.* %s %s %s FROM web_article INNER JOIN(
|
|
SELECT id, row_num FROM RankedArticles %s
|
|
) AS LimitedRanked ON LimitedRanked.id = web_article.id
|
|
ORDER BY LimitedRanked.row_num ASC LIMIT %d
|
|
`, sql, praise, collect, text_count, cursor, limit)
|
|
|
|
fmt.Println(sql)
|
|
|
|
if err := db.Raw(sql).Scan(&games).Error; err != nil {
|
|
fmt.Println("获取游戏列表失败", err)
|
|
return nil, err
|
|
}
|
|
|
|
if funk.Contains(fields, "user") {
|
|
var ids []int
|
|
for _, game := range games {
|
|
ids = append(ids, game.UserId)
|
|
}
|
|
ids = funk.UniqInt(ids)
|
|
|
|
var users []User
|
|
if err := db.Table("web_member").Where("id in (?)", ids).Find(&users).Error; err != nil {
|
|
fmt.Println("获取用户信息失败", err)
|
|
return nil, err
|
|
}
|
|
|
|
for index, game := range games {
|
|
for _, user := range users {
|
|
if game.UserId == user.ID {
|
|
games[index].User = user
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if funk.Contains(fields, "text_list") || funk.Contains(fields, "text_count") {
|
|
fmt.Println("获取游戏文字列表")
|
|
for index, item := range games {
|
|
var images []Image
|
|
if err := db.Table("web_images").Where("article_id", item.ID).Find(&images).Error; err != nil {
|
|
fmt.Println("获取游戏图片列表失败", err)
|
|
return nil, err
|
|
}
|
|
for _, image := range images {
|
|
for _, text := range image.Text {
|
|
item.TextList = append(item.TextList, text.Text)
|
|
}
|
|
}
|
|
games[index].TextList = funk.UniqString(item.TextList)
|
|
games[index].TextCount = len(item.TextList)
|
|
}
|
|
}
|
|
|
|
var items = ListItem(p.Info.FieldASTs[0].SelectionSet.Selections)
|
|
if funk.Contains(items, "views") {
|
|
type ApiResponse struct {
|
|
ID int `json:"id"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
// 0. 收集要查询的 ID
|
|
var ids []int
|
|
for x := range games {
|
|
ids = append(ids, games[x].ID)
|
|
}
|
|
idx := strings.Trim(strings.Replace(fmt.Sprint(ids), " ", ",", -1), "[]")
|
|
|
|
// 1. 发送 GET 请求
|
|
resp, err := http.Get("http://localhost:6005/api/get_views/文章?ids=" + idx)
|
|
if err != nil {
|
|
fmt.Println("Error making GET request:", err)
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// 2. 检查 HTTP 状态码
|
|
if resp.StatusCode != http.StatusOK {
|
|
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
|
|
return nil, err
|
|
}
|
|
|
|
// 3. 读取响应体
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
fmt.Println("Error reading response body:", err)
|
|
return nil, err
|
|
}
|
|
|
|
// 4. 解析 JSON 数据到结构体
|
|
var data []ApiResponse
|
|
err = json.Unmarshal(body, &data)
|
|
if err != nil {
|
|
fmt.Println("Error unmarshalling JSON:", err)
|
|
return nil, err
|
|
}
|
|
|
|
// 5. 赋值到数据集
|
|
for _, item := range data {
|
|
for i := range games {
|
|
if games[i].ID == item.ID {
|
|
games[i].Views = item.Count
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"list": games,
|
|
"total": total,
|
|
}, err
|
|
},
|
|
}
|