增加 views
This commit is contained in:
59
api/game.go
59
api/game.go
@@ -1,7 +1,10 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -38,6 +41,7 @@ type Game struct {
|
||||
Emoji3 int `json:"emoji3"`
|
||||
Emoji4 int `json:"emoji4"`
|
||||
Emoji5 int `json:"emoji5"`
|
||||
Views int `json:"views"`
|
||||
}
|
||||
|
||||
func (Game) TableName() string {
|
||||
@@ -70,6 +74,7 @@ var gameType = graphql.NewObject(graphql.ObjectConfig{
|
||||
"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: "浏览量"},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -251,6 +256,60 @@ var GameItems = &graphql.Field{
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
|
Reference in New Issue
Block a user