Full refactor of codebase
This commit is contained in:
32
src/repository/lookup.go
Normal file
32
src/repository/lookup.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/ascyii/qrank/src/utils"
|
||||
)
|
||||
|
||||
func EnsureUniqueUsernameAndSlug(u *User) error {
|
||||
baseU := u.Username
|
||||
baseS := utils.Slugify(u.Username)
|
||||
for i := range 5 {
|
||||
candU := baseU
|
||||
candS := baseS
|
||||
if i > 0 {
|
||||
suffix := "-" + utils.MustRandToken(1)
|
||||
candU = baseU + suffix
|
||||
candS = baseS + suffix
|
||||
}
|
||||
var cnt int64
|
||||
db.Model(&User{}).Where("username = ?", candU).Count(&cnt)
|
||||
if cnt == 0 {
|
||||
db.Model(&User{}).Where("slug = ?", candS).Count(&cnt)
|
||||
if cnt == 0 {
|
||||
u.Username = candU
|
||||
u.Slug = candS
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.New("cannot create unique username/slug")
|
||||
}
|
||||
Reference in New Issue
Block a user