API分页

This commit is contained in:
2024-12-02 06:53:52 +08:00
parent 520e3bade6
commit f4bec98b7a
10 changed files with 1385 additions and 1446 deletions

158
api/article.go Normal file
View File

@@ -0,0 +1,158 @@
package api
import (
"fmt"
"log"
"regexp"
"time"
"github.com/doug-martin/goqu/v9"
"github.com/graphql-go/graphql"
)
type Article struct {
ID int `json:"id" db:"id" gorm:"primaryKey"`
Title string `json:"title" db:"title"`
Orientation string `json:"orientation" db:"orientation"`
Device string `json:"device" db:"device"`
Era string `json:"era" db:"era"`
Tags string `json:"tags" db:"tags"`
UserId int `json:"user_id" db:"user_id"`
User User `json:"user" gorm:"foreignKey:UserId"`
CreateTime time.Time `json:"create_time" db:"create_time"`
UpdateTime time.Time `json:"update_time" db:"update_time"`
}
func (Article) TableName() string {
return "web_article"
}
var articleType = graphql.NewObject(graphql.ObjectConfig{
Name: "Article",
Description: "文章",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int, Description: "ID"},
"title": &graphql.Field{Type: graphql.String, Description: "标题"},
"orientation": &graphql.Field{Type: graphql.String, Description: "方向"},
"device": &graphql.Field{Type: graphql.String, Description: "设备"},
"era": &graphql.Field{Type: graphql.String, Description: "游戏上线年份"},
"tags": &graphql.Field{Type: graphql.String, Description: "标签"},
"user": &graphql.Field{Type: userType, Description: "所属用户"},
"create_time": &graphql.Field{Type: graphql.DateTime, Description: "创建时间"},
"update_time": &graphql.Field{Type: graphql.DateTime, Description: "更新时间"},
"text_count": &graphql.Field{Type: graphql.Int, Description: "文字数量", Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var count int64
err := db.Table("web_images").Where("article_id = ?", p.Source.(Article).ID).Where("text != ''").Count(&count).Error
return int(count), err
}},
},
})
var ArticleItem = &graphql.Field{
Name: "article",
Description: "单篇文章",
Type: articleType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "根据ID获取文章"},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
article := Article{ID: p.Args["id"].(int)}
if err := db.First(&article).Error; err != nil {
log.Println("获取文章失败", err)
return nil, err
}
return article, nil
},
}
var ArticleItems = &graphql.Field{
Name: "articles",
Description: "文章列表",
Type: graphql.NewObject(graphql.ObjectConfig{
Name: "ArticleConnection",
Description: "条件筛选文章列表",
Fields: graphql.Fields{
"list": &graphql.Field{Type: graphql.NewList(articleType), 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: "筛选文章中含有指定标题的"},
"tags": &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.String, Description: "翻页参数(傳回清單中指定遊標之後的元素)"},
"before": &graphql.ArgumentConfig{Type: graphql.String, Description: "翻页参数(傳回清單中指定遊標之前的元素)"},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var articles []Article
var total int
var err error
var query = goqu.Dialect("mysql").From("web_article")
// 筛选条件
for _, format := range []string{"id", "style", "device", "orientation", "era", "category_id", "tags"} {
if p.Args[format] != nil {
query = query.Where(goqu.C(format).Eq(p.Args[format]))
}
}
// 排序条件
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())
}
}
// 如果没有外部排序则使用指定排序(正则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_images.id", goqu.L(
fmt.Sprintf("ROW_NUMBER() OVER(ORDER BY web_images.%s %s)", sort, p.Args["order"]),
).As("row_num"))
}
// 取所有数据的前N条
sql, _, _ := query.Where(goqu.Ex{"article_category_top_id": 9}).ToSQL()
fmt.Println(sql)
// 遊標截取篩選結果集的前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)
}
sql = fmt.Sprintf(`
WITH RankedArticles AS (%s)
SELECT * FROM web_images INNER JOIN(
SELECT id, row_num FROM RankedArticles %s
) AS LimitedRanked ON LimitedRanked.id = web_images.id
ORDER BY LimitedRanked.row_num ASC LIMIT %d
`, sql, cursor, limit)
if err := db.Limit(limit).Where("category_top_id = 9").Find(&articles).Error; err != nil {
return nil, err
}
return map[string]interface{}{
"list": articles,
"total": total,
}, err
},
}