reCoreD-UI/controllers/record.go

86 lines
1.8 KiB
Go
Raw Normal View History

2024-04-03 09:05:12 +00:00
package controllers
import (
"fmt"
"reCoreD-UI/models"
"gorm.io/gorm"
)
2024-04-07 05:08:30 +00:00
func (c *Controller) CreateRecord(r *models.Record) (*models.Record, error) {
2024-04-03 09:05:12 +00:00
if r.RecordType != models.RecordTypeSOA {
domains, err := c.GetDomains(r.Zone)
if err != nil {
2024-04-07 05:08:30 +00:00
return nil, err
2024-04-03 09:05:12 +00:00
}
if len(domains) == 0 || domains[0].DomainName == r.Zone {
2024-04-07 05:08:30 +00:00
return nil, fmt.Errorf("no such domain")
2024-04-03 09:05:12 +00:00
}
}
2024-04-07 05:08:30 +00:00
if err := c.DB.Transaction(func(tx *gorm.DB) error {
2024-04-03 09:05:12 +00:00
return tx.Create(r).Error
2024-04-07 05:08:30 +00:00
}); err != nil {
return nil, err
}
return r, nil
2024-04-03 09:05:12 +00:00
}
func (c *Controller) CreateRecords(rs []*models.Record) error {
return c.DB.Transaction(func(tx *gorm.DB) error {
for _, r := range rs {
if err := tx.Create(r).Error; err != nil {
return err
}
}
return nil
})
}
2024-04-03 14:37:15 +00:00
func (c *Controller) GetRecords(cond map[string]string) ([]models.Record, error) {
2024-04-03 09:05:12 +00:00
var records []models.Record
if err := c.DB.Where(cond).Find(&records).Error; err != nil {
return nil, err
}
return records, nil
}
func (c *Controller) UpdateRecord(r *models.Record) error {
return c.DB.Transaction(func(tx *gorm.DB) error {
return tx.Model(r).Updates(r).Error
})
}
2024-04-03 14:37:15 +00:00
func (c *Controller) DeleteRecord(domain, id string) error {
2024-04-03 09:05:12 +00:00
return c.DB.Transaction(func(tx *gorm.DB) error {
2024-04-03 14:37:15 +00:00
return tx.Where("record_type != ?", models.RecordTypeSOA).
Where("id = ?", id).
Where("zone = ?", domain).
Delete(&models.Record{}).Error
2024-04-03 09:05:12 +00:00
})
}
2024-04-07 02:07:26 +00:00
func (c *Controller) getRecordCounts() (map[string]float64, error) {
rows, err := c.DB.Model(models.Record{}).Select("zone", "count(*) as count").Group("zone").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[string]float64)
for rows.Next() {
var domain string
var count int64
if err := rows.Scan(&domain, &count); err != nil {
return nil, err
}
result[domain] = float64(count)
}
return result, nil
}