diff --git a/internal/postgres/user.go b/internal/postgres/user.go index 676bfa4..f15b077 100644 --- a/internal/postgres/user.go +++ b/internal/postgres/user.go @@ -272,3 +272,47 @@ func GetUserFavoriteNodeWithPagination(ctx context.Context, db *gorm.DB, anthrov return &graphModels.FavoriteList{Posts: favoritePosts}, nil } + +func GetUserTagNodeWitRelationToFavedPosts(ctx context.Context, db *gorm.DB, anthroveUserID models.AnthroveUserID) ([]graphModels.TagsWithFrequency, error) { + var userFavorites []pgModels.UserFavorite + err := db.WithContext(ctx).Where("user_id = ?", string(anthroveUserID)).Find(&userFavorites).Error + if err != nil { + log.WithFields(log.Fields{ + "anthrove_user_id": anthroveUserID, + }).Error("database: failed to get user favorites") + return nil, err + } + + tagFrequency := make(map[string]int) + for _, userFavorite := range userFavorites { + var postTags []pgModels.Tag + err = db.WithContext(ctx).Model(&pgModels.Post{}).Where("id = ?", userFavorite.PostID).Association("Tags").Find(&postTags) + if err != nil { + log.WithFields(log.Fields{ + "post_id": userFavorite.PostID, + }).Error("database: failed to get post tags") + return nil, err + } + + for _, tag := range postTags { + tagFrequency[tag.Name]++ + } + } + + var tagsWithFrequency []graphModels.TagsWithFrequency + for tagName, frequency := range tagFrequency { + tagsWithFrequency = append(tagsWithFrequency, graphModels.TagsWithFrequency{ + Frequency: int64(frequency), + Tags: graphModels.AnthroveTag{ + Name: tagName, + }, + }) + } + + log.WithFields(log.Fields{ + "anthrove_user_id": anthroveUserID, + "tag_amount": len(tagsWithFrequency), + }).Trace("database: got user tag node with relation to faved posts") + + return tagsWithFrequency, nil +} diff --git a/pkg/database/postgres.go b/pkg/database/postgres.go index a13f15d..c283bea 100644 --- a/pkg/database/postgres.go +++ b/pkg/database/postgres.go @@ -126,8 +126,7 @@ func (p *postgresqlConnection) GetUserFavoritePostsWithPagination(ctx context.Co } func (p *postgresqlConnection) GetUserTagsTroughFavedPosts(ctx context.Context, anthroveUserID models.AnthroveUserID) ([]graphModels.TagsWithFrequency, error) { - //TODO implement me - panic("implement me") + return postgres.GetUserTagNodeWitRelationToFavedPosts(ctx, p.db, anthroveUserID) } func (p *postgresqlConnection) GetAllTags(ctx context.Context) ([]graphModels.TagsWithFrequency, error) {