From 178085305da8e266e35687129f916d6ad2555242 Mon Sep 17 00:00:00 2001 From: satori Date: Tue, 24 Dec 2024 19:35:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B6=E8=97=8Fviews?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/collect.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/api/collect.go b/api/collect.go index 003d56f..ef765d0 100644 --- a/api/collect.go +++ b/api/collect.go @@ -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,