add filtering and base repository

This commit is contained in:
Fran Jurmanović
2025-05-28 19:55:11 +02:00
parent 56ef5e1484
commit 0ced45ce55
17 changed files with 567 additions and 246 deletions

View File

@@ -9,28 +9,15 @@ import (
)
type ServerRepository struct {
db *gorm.DB
*BaseRepository[model.Server, model.ServerFilter]
}
func NewServerRepository(db *gorm.DB) *ServerRepository {
return &ServerRepository{
db: db,
BaseRepository: NewBaseRepository[model.Server, model.ServerFilter](db, model.Server{}),
}
}
// GetFirst
// Gets first row from Server table.
//
// Args:
// context.Context: Application context
// Returns:
// model.ServerModel: Server object from database.
func (as ServerRepository) GetFirst(ctx context.Context, serverId int) *model.Server {
db := as.db.WithContext(ctx)
ServerModel := new(model.Server)
db.Where("id=?", serverId).First(&ServerModel)
return ServerModel
}
// GetFirstByServiceName
// Gets first row from Server table.
@@ -39,45 +26,13 @@ func (as ServerRepository) GetFirst(ctx context.Context, serverId int) *model.Se
// context.Context: Application context
// Returns:
// model.ServerModel: Server object from database.
func (as ServerRepository) GetFirstByServiceName(ctx context.Context, serviceName string) *model.Server {
db := as.db.WithContext(ctx)
ServerModel := new(model.Server)
result := db.Where("service_name=?", serviceName).First(&ServerModel)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil
func (r *ServerRepository) GetFirstByServiceName(ctx context.Context, serviceName string) (*model.Server, error) {
result := new(model.Server)
if err := r.db.WithContext(ctx).Where("service_name = ?", serviceName).First(result).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
return nil, err
}
return ServerModel
}
// GetAll
// Gets All rows from Server table.
//
// Args:
// context.Context: Application context
// Returns:
// model.ServerModel: Server object from database.
func (as ServerRepository) GetAll(ctx context.Context) *[]model.Server {
db := as.db.WithContext(ctx)
ServerModel := new([]model.Server)
db.Find(&ServerModel)
return ServerModel
}
// UpdateServer
// Updates Server row from Server table.
//
// Args:
// context.Context: Application context
// Returns:
// model.Server: Server object from database.
func (as ServerRepository) UpdateServer(ctx context.Context, body *model.Server) *model.Server {
db := as.db.WithContext(ctx)
existingServer := new(model.Server)
result := db.Where("id=?", body.ID).First(existingServer)
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
body.ID = existingServer.ID
}
db.Save(body)
return body
}
return result, nil
}