diff --git a/api/graphql.go b/api/graphql.go index 80fddf0..fdaca22 100644 --- a/api/graphql.go +++ b/api/graphql.go @@ -1,6 +1,7 @@ package api import ( + "context" "fmt" "image" "log" @@ -20,6 +21,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/mitchellh/mapstructure" "github.com/thoas/go-funk" + "github.com/zhenghaoz/gorse/client" "gorm.io/driver/mysql" "gorm.io/gorm" ) @@ -232,6 +234,11 @@ func NewSchema(config Config) (graphql.Schema, error) { "user": &graphql.Field{Type: user, 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 + }}, }, }) @@ -355,6 +362,9 @@ func NewSchema(config Config) (graphql.Schema, error) { if fieldAST.Name.Value == "list" { for _, field := range fieldAST.SelectionSet.Selections { fieldAST, _ := field.(*ast.Field) + if fieldAST.Name.Value == "text_count" { + continue + } fields = append(fields, fieldAST.Name.Value) } } @@ -630,6 +640,23 @@ func NewSchema(config Config) (graphql.Schema, error) { query = query.Where(goqu.Ex{"web_images.id": goqu.Op{"in": item}}).Select("web_images.id", goqu.L( fmt.Sprintf("ROW_NUMBER() OVER(ORDER BY FIELD(%s, %s))", "web_images.id", regexp.MustCompile(`[\[\]]`).ReplaceAllString(strings.Join(strings.Fields(fmt.Sprint(item)), ", "), "")), ).As("row_num")) + + // 收集阅读行为 + if p.Context.Value("user_id") != nil && p.Args["after"] == nil { + ctx := context.Background() + user_id := p.Context.Value("user_id").(int) + + feedbacks := []client.Feedback{{ + FeedbackType: "read", + UserId: fmt.Sprintf("%s", user_id), + ItemId: fmt.Sprintf("%s", p.Args["Similar"]), + Timestamp: time.Now().Format("2006-01-02 15:04:05"), + }} + + if _, err := gorse.InsertFeedback(ctx, feedbacks); err != nil { + fmt.Println("写入阅读记录失败", err) + } + } } // 筛选:兴趣推荐 @@ -1002,6 +1029,22 @@ func NewSchema(config Config) (graphql.Schema, error) { return img, nil }, }, + "article": &graphql.Field{ + Name: "article", + Description: "单篇文章", + Type: article, + 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 + }, + }, }})}) if err != nil { return schema, err