Skip to content

Commit

Permalink
refactor: more ent
Browse files Browse the repository at this point in the history
  • Loading branch information
Vilsol committed Dec 4, 2023
1 parent bd732ea commit f70210a
Show file tree
Hide file tree
Showing 44 changed files with 2,400 additions and 1,193 deletions.
214 changes: 0 additions & 214 deletions db/postgres/mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,9 @@ package postgres
import (
"context"
"fmt"
"math"
"strings"
"time"

"github.com/patrickmn/go-cache"
"gorm.io/gorm"

"github.com/satisfactorymodding/smr-api/generated"
"github.com/satisfactorymodding/smr-api/models"
"github.com/satisfactorymodding/smr-api/util"
)

func GetModByID(ctx context.Context, modID string) *Mod {
Expand All @@ -37,24 +30,6 @@ func GetModByIDNoCache(ctx context.Context, modID string) *Mod {
return &mod
}

func GetModByReference(ctx context.Context, modReference string) *Mod {
cacheKey := "GetModByReference_" + modReference
if mod, ok := dbCache.Get(cacheKey); ok {
return mod.(*Mod)
}

var mod Mod
DBCtx(ctx).Preload("Tags").Preload("Versions.Targets").Find(&mod, "mod_reference = ?", modReference)

if mod.ID == "" {
return nil
}

dbCache.Set(cacheKey, &mod, cache.DefaultExpiration)

return &mod
}

func GetModsByID(ctx context.Context, modIds []string) []Mod {
cacheKey := "GetModsById_" + strings.Join(modIds, ":")
if mods, ok := dbCache.Get(cacheKey); ok {
Expand All @@ -73,12 +48,6 @@ func GetModsByID(ctx context.Context, modIds []string) []Mod {
return mods
}

func DeleteMod(ctx context.Context, modID string) {
DBCtx(ctx).Delete(Mod{}, "id = ?", modID)
DBCtx(ctx).Delete(Version{}, "mod_id = ?", modID)
DBCtx(ctx).Delete(UserMod{}, "mod_id = ?", modID)
}

func GetModCount(ctx context.Context, search string, unapproved bool) int64 {
cacheLey := "GetModCount_" + search + "_" + fmt.Sprint(unapproved)
if count, ok := dbCache.Get(cacheLey); ok {
Expand All @@ -99,26 +68,6 @@ func GetModCount(ctx context.Context, search string, unapproved bool) int64 {
return modCount
}

func GetModCountNew(ctx context.Context, filter *models.ModFilter, unapproved bool) int64 {
hash, err := filter.Hash()
cacheKey := ""
if err == nil {
cacheKey = "GetModCountNew_" + hash + "_" + fmt.Sprint(unapproved)
if count, ok := dbCache.Get(cacheKey); ok {
return count.(int64)
}
}

var modCount int64
NewModQuery(ctx, filter, unapproved, true).Count(&modCount)

if cacheKey != "" {
dbCache.Set(cacheKey, modCount, cache.DefaultExpiration)
}

return modCount
}

func IncrementModViews(ctx context.Context, mod *Mod) {
DBCtx(ctx).Model(mod).Update("views", mod.Views+1)
}
Expand Down Expand Up @@ -151,118 +100,6 @@ func GetMods(ctx context.Context, limit int, offset int, orderBy string, order s
return mods
}

func GetModsNew(ctx context.Context, filter *models.ModFilter, unapproved bool) []Mod {
hash, err := filter.Hash()
cacheKey := ""
if err == nil {
cacheKey = "GetModsNew_" + hash + "_" + fmt.Sprint(unapproved)
if mods, ok := dbCache.Get(cacheKey); ok {
return mods.([]Mod)
}
}

var mods []Mod
NewModQuery(ctx, filter, unapproved, false).Find(&mods)

if cacheKey != "" {
dbCache.Set(cacheKey, mods, cache.DefaultExpiration)
}

return mods
}

func CreateMod(ctx context.Context, mod *Mod) (*Mod, error) {
// Allow only new 4 mods per 24h

mod.ID = util.GenerateUniqueID()

var mods []Mod
DBCtx(ctx).Order("created_at asc").Find(&mods, "creator_id = ? AND created_at > ?", mod.CreatorID, time.Now().Add(time.Hour*24*-1))

currentAvailable := float64(4)
lastModTime := time.Now()
for _, mod := range mods {
currentAvailable--
if mod.CreatedAt.After(lastModTime) {
diff := mod.CreatedAt.Sub(lastModTime)
currentAvailable = math.Min(4, currentAvailable+diff.Hours()/6)
}
lastModTime = mod.CreatedAt
}

if currentAvailable < 1 {
timeToWait := time.Until(lastModTime.Add(time.Hour * 6)).Minutes()
return nil, fmt.Errorf("please wait %.0f minutes to post another mod", timeToWait)
}

DBCtx(ctx).Create(&mod)
DBCtx(ctx).Create(&UserMod{
Role: "creator",
ModID: mod.ID,
UserID: mod.CreatorID,
})

return mod, nil
}

func NewModQuery(ctx context.Context, filter *models.ModFilter, unapproved bool, count bool) *gorm.DB {
query := DBCtx(ctx)

if count {
query = query.Model(Mod{})
}

query = query.Where("approved = ? AND denied = ?", !unapproved, false)
query = query.Preload("Tags").Preload("Versions.Targets")
if filter != nil {
if filter.Search != nil && *filter.Search != "" {
cleanSearch := strings.ReplaceAll(strings.TrimSpace(*filter.Search), " ", " & ")
sub := DBCtx(ctx).Table("mods")
sub = sub.Select("id, (similarity(name, ?) * 2 + similarity(short_description, ?) + similarity(full_description, ?) * 0.5) as s", cleanSearch, cleanSearch, cleanSearch)

query = query.Joins("INNER JOIN (?) AS t1 on t1.id = mods.id", sub)
query = query.Where("t1.s > 0.2")

if !count && *filter.OrderBy == generated.ModFieldsSearch {
query = query.Order("t1.s DESC")
}
}

if !count {
query = query.Limit(*filter.Limit).
Offset(*filter.Offset)

if *filter.OrderBy != generated.ModFieldsSearch {
if string(*filter.OrderBy) == "last_version_date" {
query = query.Order("case when last_version_date is null then 1 else 0 end, last_version_date " + string(*filter.Order))
} else {
query = query.Order("mods." + string(*filter.OrderBy) + " " + string(*filter.Order))
}
}
}

if filter.Hidden == nil || !(*filter.Hidden) {
query = query.Where("hidden = false")
}

if filter.Ids != nil && len(filter.Ids) > 0 {
query = query.Where("mods.id in (?)", filter.Ids)
} else if filter.References != nil && len(filter.References) > 0 {
query = query.Where("mod_reference in (?)", filter.References)
}

if filter.Fields != nil && len(filter.Fields) > 0 {
query = query.Select(filter.Fields)
}

if filter.TagIDs != nil && len(filter.TagIDs) > 0 {
query.Joins("INNER JOIN mod_tags on mod_tags.tag_id in ? AND mod_tags.mod_id = mods.id", filter.TagIDs)
}
}

return query.Debug()
}

func GetModByIDOrReference(ctx context.Context, modIDOrReference string) *Mod {
cacheKey := "GetModByIDOrReference_" + modIDOrReference
if mod, ok := dbCache.Get(cacheKey); ok {
Expand All @@ -280,54 +117,3 @@ func GetModByIDOrReference(ctx context.Context, modIDOrReference string) *Mod {

return &mod
}

func ClearModTags(ctx context.Context, modID string) error {
r := DBCtx(ctx).Where("mod_id = ?", modID).Delete(&ModTag{})
return r.Error
}

func SetModTags(ctx context.Context, modID string, tagIDs []string) error {
for _, tag := range tagIDs {
err := AddModTag(ctx, modID, tag)
if err != nil {
return err
}
}
return nil
}

func ResetModTags(ctx context.Context, modID string, tagIDs []string) error {
err := ClearModTags(ctx, modID)
if err != nil {
return err
}
err = SetModTags(ctx, modID, tagIDs)
if err != nil {
return err
}
return nil
}

func AddModTag(ctx context.Context, modID string, tagID string) error {
r := DBCtx(ctx).Create(&ModTag{ModID: modID, TagID: tagID})
return r.Error
}

func RemoveModTag(ctx context.Context, modID string, tagID string) error {
r := DBCtx(ctx).Delete(&ModTag{ModID: modID, TagID: tagID})
return r.Error
}

func GetModsByIDOrReference(ctx context.Context, modIDOrReferences []string) []Mod {
cacheKey := "GetModsByIDOrReference_" + strings.Join(modIDOrReferences, "-")
if mod, ok := dbCache.Get(cacheKey); ok {
return mod.([]Mod)
}

var mods []Mod
DBCtx(ctx).Preload("Tags").Find(&mods, "mod_reference IN ? OR id IN ?", modIDOrReferences, modIDOrReferences)

dbCache.Set(cacheKey, mods, cache.DefaultExpiration)

return mods
}
14 changes: 0 additions & 14 deletions db/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,6 @@ func Save(ctx context.Context, object interface{}) {
DBCtx(ctx).Save(object)
}

func Delete(ctx context.Context, object interface{}) {
DBCtx(ctx).Delete(object)
ClearCache()
}

func DeleteForced(ctx context.Context, object interface{}) {
DBCtx(ctx).Unscoped().Delete(object)
ClearCache()
}

func DBCtx(ctx context.Context) *gorm.DB {
if ctx != nil {
dbCtx := DBFromContext(ctx)
Expand All @@ -141,10 +131,6 @@ func DBCtx(ctx context.Context) *gorm.DB {
return db
}

func ClearCache() {
dbCache.Flush()
}

func EnableDebug() {
if db != nil {
db = db.Debug()
Expand Down
28 changes: 0 additions & 28 deletions db/postgres/postgres_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,24 +108,6 @@ func (TinyVersion) TableName() string {
return "versions"
}

type Guide struct {
SMRModel
Name string `gorm:"type:varchar(50)"`
ShortDescription string `gorm:"type:varchar(128)"`
Guide string
UserID string
Tags []Tag `gorm:"many2many:guide_tags"`
User User
Views uint
}

type UserGroup struct {
SMRDates

UserID string `gorm:"primary_key"`
GroupID string `gorm:"primary_key"`
}

type SMLVersion struct {
Date time.Time
BootstrapVersion *string
Expand Down Expand Up @@ -157,16 +139,6 @@ type Tag struct {
Mods []Mod `gorm:"many2many:mod_tags"`
}

type ModTag struct {
TagID string `gorm:"primary_key;type:varchar(24)"`
ModID string `gorm:"primary_key;type:varchar(16)"`
}

type GuideTag struct {
TagID string `gorm:"primary_key;type:varchar(24)"`
GuideID string `gorm:"primary_key;type:varchar(16)"`
}

type CompatibilityInfo struct {
Ea Compatibility `gorm:"type:compatibility" json:"EA"`
Exp Compatibility `gorm:"type:compatibility" json:"EXP"`
Expand Down
Loading

0 comments on commit f70210a

Please sign in to comment.