Skip to content

Commit

Permalink
feat(api): speed up sorting on Explore page
Browse files Browse the repository at this point in the history
🚀 🚀 🚀 🚀 🚀 🚀
  • Loading branch information
vednoc committed Aug 4, 2021
1 parent 6e2a8e5 commit 344168b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
2 changes: 1 addition & 1 deletion models/stats.go
Expand Up @@ -17,7 +17,7 @@ type Stats struct {
gorm.Model
Hash string `gorm:"unique"`
Style Style
StyleID int
StyleID int `gorm:"index"`
Install time.Time `gorm:"default:null"`
View time.Time `gorm:"default:null"`
}
Expand Down
25 changes: 12 additions & 13 deletions models/style.go
Expand Up @@ -2,7 +2,6 @@ package models

import (
"fmt"
stdstrings "strings"
"time"

"gorm.io/gorm"
Expand Down Expand Up @@ -219,27 +218,28 @@ func GetAllAvailableStylesPaginated(page int, orderStatement string) ([]StyleCar
size := 40
offset := (page - 1) * size

// Reflection go brrrr.
nums := []struct {
ID, Views, Installs int
}{}

var stmt string
if stdstrings.HasPrefix(orderStatement, "installs") {
stmt += "styles.id, "
stmt += "(select count(*) from stats s where s.style_id = styles.id and s.install) installs"
} else if stdstrings.HasPrefix(orderStatement, "views") {
stmt += "styles.id, "
stmt += "(select count(*) from stats s where s.style_id = styles.id and s.view) views"
} else {
if strings.HasPrefix(orderStatement, "styles") {
stmt += "styles.id, styles.created_at, styles.updated_at"
} else if strings.HasPrefix(orderStatement, "views") {
stmt += "styles.id, (select count(*) from stats s where s.view > 0 and s.style_id = styles.id) views"
} else {
stmt += "styles.id, (select count(*) from stats s where s.install > 0 and s.style_id = styles.id) installs"
}

nums := new([]StyleCard)
err := database.Conn.
Select(stmt).Joins("join users u on u.id = styles.user_id").
Table("styles").Order(orderStatement).Offset(offset).Limit(size).Find(&nums).Error
Select(stmt).Table("styles").Order(orderStatement).Offset(offset).Limit(size).Find(&nums).Error
if err != nil {
return nil, err
}

var styleIDs []int
for _, partial := range *nums {
for _, partial := range nums {
styleIDs = append(styleIDs, int(partial.ID))
}

Expand All @@ -248,7 +248,6 @@ func GetAllAvailableStylesPaginated(page int, orderStatement string) ([]StyleCar
stmt += "(select count(id) from stats s where s.style_id = styles.id and s.view > 0) views"

err = database.Conn.
Debug().
Select(stmt).Table("styles").Joins("join users u on u.id = styles.user_id").
Order(orderStatement).Find(&q, styleIDs).Error
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions utils/strings/strings.go
Expand Up @@ -27,3 +27,7 @@ func QueryUnescape(s string) string {

return s
}

func HasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
}

0 comments on commit 344168b

Please sign in to comment.