收藏views
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/graphql-go/graphql"
|
||||
@@ -29,6 +33,7 @@ type Collection struct {
|
||||
User User `json:"user" gorm:"foreignKey:UserId;references:ID"`
|
||||
Fan bool `json:"praise" gorm:"-"`
|
||||
Covers []Cover `json:"covers" gorm:"-"`
|
||||
Views int `json:"views"`
|
||||
}
|
||||
|
||||
func (Collection) TableName() string {
|
||||
@@ -68,6 +73,7 @@ var CollectionItems = &graphql.Field{
|
||||
})),
|
||||
Description: "封面集",
|
||||
},
|
||||
"views": &graphql.Field{Type: graphql.Int, Description: "浏览量"},
|
||||
},
|
||||
})), Description: "收藏夹列表"},
|
||||
"total": &graphql.Field{Type: graphql.Int, Description: "收藏夹总数"},
|
||||
@@ -135,6 +141,59 @@ var CollectionItems = &graphql.Field{
|
||||
collects[index].Covers = data
|
||||
}
|
||||
|
||||
if funk.Contains(items, "views") {
|
||||
type ApiResponse struct {
|
||||
ID int `json:"id"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// 0. 收集要查询的 ID
|
||||
var ids []int
|
||||
for x := range collects {
|
||||
ids = append(ids, collects[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 collects {
|
||||
if collects[i].ID == item.ID {
|
||||
collects[i].Views = item.Count
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"list": collects,
|
||||
"total": total,
|
||||
|
Reference in New Issue
Block a user