You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
2.1 KiB

package Database
import (
"errors"
"fmt"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func GetUserById(id string) (Models.User, error) {
var (
userData Models.User
err error
)
err = DB.Preload(clause.Associations).
First(&userData, "id = ?", id).
Error
userData.Password = ""
return userData, err
}
func GetUserByEmail(email string) (Models.User, error) {
var (
userData Models.User
err error
)
err = DB.Preload(clause.Associations).
First(&userData, "email = ?", email).
Error
return userData, err
}
func GetUsers(page, pageSize int, search string) ([]Models.User, error) {
var (
users []Models.User
query *gorm.DB
offset int
i int
err error
)
switch {
case pageSize > 100:
pageSize = 100
case pageSize <= 0:
pageSize = 10
}
offset = page * pageSize
search = fmt.Sprintf("%%%s%%", search)
query = DB.Model(Models.User{}).
Offset(offset).
Limit(pageSize).
Order("created_at desc")
if search != "" {
query = query.
Where("CONCAT_WS(' ', first_name, last_name) LIKE ?", search).
Or("email LIKE ?", search)
}
err = query.
Find(&users).
Error
for i, _ = range users {
users[i].Password = ""
}
return users, err
}
func CheckUniqueEmail(email string) error {
var (
exists bool
err error
)
err = DB.Model(Models.User{}).
Select("count(*) > 0").
Where("email = ?", email).
Find(&exists).
Error
if err != nil {
return err
}
if exists {
return errors.New("Invalid email")
}
return nil
}
func CreateUser(userData *Models.User) error {
var (
err error
)
err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
Create(userData).
Error
userData.Password = ""
return err
}
func UpdateUser(id string, userData *Models.User) error {
var (
err error
)
err = DB.Model(&userData).
Omit("id", "created_at", "updated_at", "deleted_at").
Where("id = ?", id).
Updates(userData).
Error
userData.Password = ""
return err
}
func DeleteUser(userData *Models.User) error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(userData).
Error
}