diff --git a/api/graphql.go b/api/graphql.go index 2e0b82b..7841b1f 100644 --- a/api/graphql.go +++ b/api/graphql.go @@ -222,6 +222,21 @@ func NewSchema(config Config) (graphql.Schema, error) { return fields } + orderType := graphql.NewEnum(graphql.EnumConfig{ + Name: "OrderType", + Description: "排序类型", + Values: graphql.EnumValueConfigMap{ + "ASC": &graphql.EnumValueConfig{ + Value: "ASC", + Description: "升序", + }, + "DESC": &graphql.EnumValueConfig{ + Value: "DESC", + Description: "降序", + }, + }, + }) + schema, err := graphql.NewSchema(graphql.SchemaConfig{Query: graphql.NewObject(graphql.ObjectConfig{Name: "RootQuery", Fields: graphql.Fields{ "categorys": &graphql.Field{ Name: "categorys", @@ -353,6 +368,8 @@ func NewSchema(config Config) (graphql.Schema, error) { }, }), Args: graphql.FieldConfigArgument{ + "sort": &graphql.ArgumentConfig{Type: graphql.String, Description: "排序方法"}, + "order": &graphql.ArgumentConfig{Type: orderType, Description: "排序方向", DefaultValue: "ASC"}, "orientation": &graphql.ArgumentConfig{Type: graphql.String, Description: "筛选横屏竖屏图像"}, "follower": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取指定ID用户的关注列表发布的图像"}, "interest": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取指定ID用户的兴趣推荐图像"}, @@ -390,6 +407,8 @@ func NewSchema(config Config) (graphql.Schema, error) { Similar int Follower int Orientation string + Sort string + Order string } mapstructure.Decode(p.Args, &args) @@ -411,7 +430,7 @@ func NewSchema(config Config) (graphql.Schema, error) { // 筛选条件 for _, format := range argFormat { if p.Args[format] != nil { - query = query.Where(fmt.Sprintf(format, " = ?"), p.Args[format]) + query = query.Where(fmt.Sprintf("%s = ?", format), p.Args[format]) } } @@ -522,6 +541,11 @@ func NewSchema(config Config) (graphql.Schema, error) { total = len(list) + var count int64 + if len(list) > 0 { + query = query.Count(&count) + } + // 截取: 分页 if args.After != 0 { index := -1 @@ -575,12 +599,21 @@ func NewSchema(config Config) (graphql.Schema, error) { query = query.Preload(item) } + // 排序规则 + if args.Sort != "" && args.Order != "" { + query = query.Order(fmt.Sprintf("%s %s", args.Sort, args.Order)) + } + // 输出(游戏截图分类ID为22) if err := query.Where("article_category_top_id = 22").Find(&images).Error; err != nil { fmt.Println("获取图像列表失败", err) return nil, err } + if total == 0 && count > 0 { + total = int(count) + } + return map[string]interface{}{ "list": images, "total": total,