initial commit
This commit is contained in:
81
internal/repository/postgres/auth/role.go
Normal file
81
internal/repository/postgres/auth/role.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.uber.org/fx"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
domainAuth "base/internal/domain/auth"
|
||||
)
|
||||
|
||||
type roleRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewRoleRepository(lc fx.Lifecycle, db *gorm.DB) domainAuth.RoleRepository {
|
||||
lc.Append(
|
||||
fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
return db.AutoMigrate(&domainAuth.Role{})
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
return nil
|
||||
},
|
||||
})
|
||||
return &roleRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *roleRepository) Create(ctx context.Context, role *domainAuth.Role) error {
|
||||
model := toRoleModel(role)
|
||||
if err := r.db.WithContext(ctx).Create(model).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return copyRoleFromModel(role, model)
|
||||
}
|
||||
|
||||
func (r *roleRepository) FindByID(ctx context.Context, id uuid.UUID) (*domainAuth.Role, error) {
|
||||
var model RoleModel
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&model).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRoleDomain(&model), nil
|
||||
}
|
||||
|
||||
func (r *roleRepository) FindByName(ctx context.Context, name string) (*domainAuth.Role, error) {
|
||||
var model RoleModel
|
||||
if err := r.db.WithContext(ctx).Where("name = ?", name).First(&model).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRoleDomain(&model), nil
|
||||
}
|
||||
|
||||
func (r *roleRepository) Update(ctx context.Context, role *domainAuth.Role) error {
|
||||
model := toRoleModel(role)
|
||||
return r.db.WithContext(ctx).Model(&RoleModel{}).Where("id = ?", role.ID).Updates(model).Error
|
||||
}
|
||||
|
||||
func (r *roleRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
return r.db.WithContext(ctx).Delete(&RoleModel{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *roleRepository) List(ctx context.Context, limit, offset int) ([]*domainAuth.Role, error) {
|
||||
var models []RoleModel
|
||||
if err := r.db.WithContext(ctx).Limit(limit).Offset(offset).Find(&models).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roles := make([]*domainAuth.Role, len(models))
|
||||
for i, model := range models {
|
||||
roles[i] = toRoleDomain(&model)
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r *roleRepository) Count(ctx context.Context) (int64, error) {
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).Model(&RoleModel{}).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
Reference in New Issue
Block a user