-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathdomains.go
93 lines (82 loc) · 2.42 KB
/
domains.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package dao
import (
"context"
"fmt"
"github.com/content-services/content-sources-backend/pkg/candlepin_client"
"github.com/content-services/content-sources-backend/pkg/config"
"github.com/content-services/content-sources-backend/pkg/models"
"github.com/content-services/content-sources-backend/pkg/pulp_client"
"github.com/labstack/gommon/random"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type domainDaoImpl struct {
db *gorm.DB
pulpClient pulp_client.PulpGlobalClient
cpClient candlepin_client.CandlepinClient
}
func GetDomainDao(db *gorm.DB,
pulpClient pulp_client.PulpGlobalClient,
candlepinClient candlepin_client.CandlepinClient) DomainDao {
// Return DAO instance
return domainDaoImpl{
db: db,
pulpClient: pulpClient,
cpClient: candlepinClient,
}
}
func (dDao domainDaoImpl) FetchOrCreateDomain(ctx context.Context, orgId string) (string, error) {
dName, err := dDao.Fetch(ctx, orgId)
if err != nil {
return "", err
} else if dName != "" {
return dName, nil
}
return dDao.Create(ctx, orgId)
}
func (dDao domainDaoImpl) Create(ctx context.Context, orgId string) (string, error) {
name := fmt.Sprintf("cs-%v", random.New().String(10, random.Hex))
if orgId == config.RedHatOrg {
name = config.RedHatDomainName
}
toCreate := models.Domain{
DomainName: name,
OrgId: orgId,
}
result := dDao.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "org_id"}},
DoNothing: true,
}).Create(&toCreate)
if result.Error != nil {
return "", result.Error
} else {
return dDao.Fetch(ctx, orgId)
}
}
func (dDao domainDaoImpl) Fetch(ctx context.Context, orgId string) (string, error) {
var found []models.Domain
result := dDao.db.WithContext(ctx).Where("org_id = ?", orgId).Find(&found)
if result.Error != nil {
return "", result.Error
}
if len(found) != 1 {
return "", nil
}
return found[0].DomainName, nil
}
func (dDao domainDaoImpl) List(ctx context.Context) ([]models.Domain, error) {
var domains []models.Domain
result := dDao.db.WithContext(ctx).Table("domains").Find(&domains)
if result.Error != nil {
return nil, result.Error
}
return domains, nil
}
func (dDao domainDaoImpl) Delete(ctx context.Context, orgID string, domainName string) error {
var domain models.Domain
result := dDao.db.WithContext(ctx).Where("domain_name = ? AND org_id = ?", domainName, orgID).Delete(&domain)
if result.Error != nil {
return result.Error
}
return nil
}