package repository import ( "repo-pattern/app/lib/helpers" "repo-pattern/app/models" "github.com/google/uuid" "gorm.io/gorm" ) type ApiKeysRepository struct { db *gorm.DB } type ApiKeysFilter struct { Key *uuid.UUID CompanyId *uuid.UUID IsActive *bool CompanyIsActive *bool } func CreateApiKeysRepository(db *gorm.DB) *ApiKeysRepository { return &ApiKeysRepository{db} } func applyApiKeyFilter(db *gorm.DB, query *gorm.DB, filter *ApiKeysFilter) *gorm.DB { if filter.Key != nil { query.Where("key = ?", *filter.Key) } if filter.IsActive != nil { now := helpers.UTCNow() if *filter.IsActive { query.Where("active_from IS NULL OR active_from <= ?", now) query.Where("active_to IS NULL OR active_to >= ?", now) } else { query.Where( "active_from IS NOT NULL AND active_from >= ?", now, ).Or( "active_to IS NOT NULL AND active_to =< ?", now, ) } } if filter.CompanyId != nil { query.Where("company_id = ?", *filter.CompanyId) } if filter.CompanyIsActive != nil { query.Joins("Company").Where( map[string]interface{}{"Company.is_active": *filter.CompanyIsActive}, ) } return query } func (r *ApiKeysRepository) New(companyId uuid.UUID) *models.ApiKey { now := helpers.UTCNow() return &models.ApiKey{ CompanyId: companyId, ActiveFrom: &now, CreatedAt: now, UpdatedAt: now, } } func (r *ApiKeysRepository) Get(filter *ApiKeysFilter) *models.ApiKey { var api_key models.ApiKey query := r.db.Model(&models.ApiKey{}) applyApiKeyFilter(r.db, query, filter) result := query.First(&api_key).Joins("Company") if result.Error != nil { return nil } return &api_key } func (r *ApiKeysRepository) Save(model *models.ApiKey) { model.UpdatedAt = helpers.UTCNow() // we don't have standard model Id, but Key as primary key. // this could be possible reason for save not assigning generated key uuid // to model.Key. but this works. if model.Key == uuid.Nil { r.db.Create(model) } else { r.db.Save(model) } }