From 46e6cdfa52f7ae03ff0ed7d506bdca0c88311565 Mon Sep 17 00:00:00 2001 From: SoXX Date: Sun, 11 Aug 2024 00:23:47 +0200 Subject: [PATCH] feat(database): added user --- pkg/database/user.go | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 pkg/database/user.go diff --git a/pkg/database/user.go b/pkg/database/user.go new file mode 100644 index 0000000..d78505a --- /dev/null +++ b/pkg/database/user.go @@ -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 +}