feat(database): added user

This commit is contained in:
SoXX 2024-08-11 00:23:47 +02:00
parent 2b54f25eea
commit 46e6cdfa52

79
pkg/database/user.go Normal file
View File

@ -0,0 +1,79 @@
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
}