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 Cover struct { ID int `json:"id"` Type string `json:"type"` } type Collection struct { ID int `json:"id" gorm:"primaryKey"` Title string `json:"title"` Content string `json:"content"` Type string `json:"type"` Thumbnail string `json:"thumbnail"` Num int `json:"num"` Fans int `json:"fans"` UserId int `json:"user_id"` ArticleId int `json:"article_id"` CreateTime time.Time `json:"create_time"` UpdateTime time.Time `json:"update_time"` 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 { return "web_member_explorer" } var CollectionItems = &graphql.Field{ Name: "collections", Description: "收藏列表", Type: graphql.NewObject(graphql.ObjectConfig{ Name: "CollectConnection", Description: "条件筛选收藏夹列表", Fields: graphql.Fields{ "list": &graphql.Field{Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{ Name: "collection", Description: "收藏夹", Fields: graphql.Fields{ "id": &graphql.Field{Type: graphql.Int, Description: "ID"}, "type": &graphql.Field{Type: graphql.Int, Description: "类型"}, "title": &graphql.Field{Type: graphql.String, Description: "标题"}, "content": &graphql.Field{Type: graphql.String, Description: "内容"}, "thumbnail": &graphql.Field{Type: graphql.String, Description: "缩略图"}, "num": &graphql.Field{Type: graphql.Int, Description: "收藏数量"}, "create_time": &graphql.Field{Type: graphql.DateTime, Description: "创建时间"}, "update_time": &graphql.Field{Type: graphql.DateTime, Description: "更新时间"}, "fans": &graphql.Field{Type: graphql.Int, Description: "关注数"}, "fan": &graphql.Field{Type: graphql.Boolean, Description: "当前用户是否关注"}, "user": &graphql.Field{Type: userType, Description: "用户"}, "covers": &graphql.Field{ Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{ Name: "cover", Description: "封面", Fields: graphql.Fields{ "id": &graphql.Field{Type: graphql.Int, Description: "ID"}, "type": &graphql.Field{Type: graphql.String, Description: "类型"}, }, })), Description: "封面集", }, "views": &graphql.Field{Type: graphql.Int, Description: "浏览量"}, }, })), Description: "收藏夹列表"}, "total": &graphql.Field{Type: graphql.Int, Description: "收藏夹总数"}, }, }), Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "筛选收藏中指定ID的"}, "title": &graphql.ArgumentConfig{Type: graphql.String, Description: "筛选收藏中含有指定标题的"}, "type": &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 collects []Collection var total int var limit int = 10 if p.Args["first"] != nil { limit = p.Args["first"].(int) } //order := clause.OrderByColumn{ // Column: clause.Column{Name: p.Args["sort"].(string)}, // Desc: p.Args["order"].(string) == "DESC", //} var query = goqu.Dialect("mysql").From("web_member_explorer") // 筛选条件 for _, format := range []string{"id", "title", "type"} { if p.Args[format] != nil { query = query.Where(goqu.C(format).Eq(p.Args[format])) } } // 如果没有外部排序则使用指定排序(正则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_member_explorer.id", goqu.L( fmt.Sprintf("ROW_NUMBER() OVER(ORDER BY web_member_explorer.%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 user_id = p.Context.Value("user_id").(int) var items = ListItem(p.Info.FieldASTs[0].SelectionSet.Selections) var fan string if funk.Contains(items, "fan") { fan = fmt.Sprintf(",CASE WHEN EXISTS (SELECT 1 FROM web_fans WHERE web_fans.follower_id = %d AND web_fans.blogger_id = web_member_explorer.id AND web_fans.type = 3) THEN TRUE ELSE FALSE END AS is_praise", user_id) } sql = fmt.Sprintf(` WITH RankedArticles AS (%s) SELECT web_member_explorer.* %s FROM web_member_explorer INNER JOIN( SELECT id, row_num FROM RankedArticles %s ) AS LimitedRanked ON LimitedRanked.id = web_member_explorer.id ORDER BY LimitedRanked.row_num ASC LIMIT %d `, sql, fan, cursor, limit) fmt.Println(sql) if err := db.Raw(sql).Scan(&collects).Error; err != nil { fmt.Println("获取游戏列表失败", err) return nil, err } if funk.Contains(items, "user") { var ids []int for _, collect := range collects { ids = append(ids, collect.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 collects { for _, user := range users { if game.UserId == user.ID { collects[index].User = user break } } } } //if err := db.Limit(limit).Preload("User").Order(order).Find(&collects).Error; err != nil { // fmt.Println(err.Error()) // return nil, err //} //if funk.Contains(items, "fan") { // var user_id = p.Context.Value("user_id").(int) // for index, item := range collects { // var total int64 // if err := db.Table("web_fans").Where("follower_id = ? AND blogger_id = ? AND type = 3", user_id, item.ID).Count(&total).Error; err != nil { // fmt.Println(index, err.Error()) // return nil, err // } // collects[index].Fan = total > 0 // } //} for index, item := range collects { var data []Cover var t string = "article" var s string = "collect_id AS id" if item.Type == "0" { t = "image" s = "image_id AS id" } if err := db.Table("web_collect").Select(s).Limit(3).Where("explorer_id = ?", item.ID).Find(&data).Error; err != nil { fmt.Println("获取封面ID失败", err) } for i := range data { data[i].Type = t } 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, }, nil }, }