otter-space-sdk/pkg/database/user.go
2024-08-11 00:23:47 +02:00

80 lines
2.0 KiB
Go

package database
import (
"context"
"errors"
otterError "git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/error"
"git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/models"
"gorm.io/gorm"
)
func CreateUser(ctx context.Context, id models.UserID) (models.User, error) {
if client == nil {
return models.User{}, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
user := models.User{
BaseModel: models.BaseModel[models.UserID]{
ID: id,
},
}
result := client.WithContext(ctx).Create(&user)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
return models.User{}, &otterError.Database{Reason: otterError.DuplicateKey}
}
return models.User{}, result.Error
}
return user, nil
}
func GetUserByID(ctx context.Context, id models.UserID) (models.User, error) {
var user models.User
if client == nil {
return models.User{}, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
if len(id) == 0 {
return models.User{}, &otterError.EntityValidationFailed{Reason: otterError.UserIDIsEmpty}
}
if len(id) != 25 {
return models.User{}, &otterError.EntityValidationFailed{Reason: otterError.UserIDToShort}
}
result := client.WithContext(ctx).First(&user, "id = ?", id)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return models.User{}, &otterError.Database{Reason: otterError.NoDataFound}
}
return models.User{}, result.Error
}
return user, nil
}
func DeleteUser(ctx context.Context, id models.UserID) error {
var user models.User
if client == nil {
return &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
if len(id) == 0 {
return &otterError.EntityValidationFailed{Reason: otterError.UserIDIsEmpty}
}
result := client.WithContext(ctx).Delete(&user, id)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return &otterError.Database{Reason: otterError.NoDataFound}
}
return result.Error
}
return nil
}