hostname-service/rules/interface.go

62 lines
1.7 KiB
Go
Raw Normal View History

2024-01-17 18:05:55 +01:00
package rules
import (
"fmt"
"log"
"git.beisel.it/florian/hostname-service/db"
)
type HostnameRule interface {
Generate(params map[string]interface{}) (string, []byte, error)
Insert(category string, params map[string]interface{}) (string, error)
Update(category string, oldhostname string, params map[string]interface{}) (string, error)
2024-01-17 18:05:55 +01:00
}
type BaseRule struct{}
func (br *BaseRule) baseInsert(rule HostnameRule, category string, params map[string]interface{}) (string, error) {
// Generate the hostname using the passed rule's Generate method
hostname, paramsJSON, err := rule.Generate(params)
if err != nil {
return "", err
}
2024-01-17 18:05:55 +01:00
exists, err := db.HostnameExists(category, hostname)
if err != nil {
log.Printf("error checking existence of hostname: %v", err)
return "", err
2024-01-17 18:05:55 +01:00
}
if exists {
log.Printf("hostname %s does not exist in category %s", hostname, category)
return "", fmt.Errorf("hostname-exists")
2024-01-17 18:05:55 +01:00
}
// Insert the hostname into the database
2024-01-17 18:05:55 +01:00
err = db.InsertHostname(category, hostname, paramsJSON)
if err != nil {
log.Printf("Error inserting hostname into DB: %v", err)
return "", err
2024-01-17 18:05:55 +01:00
}
return hostname, nil
2024-01-17 18:05:55 +01:00
}
// baseUpdate method for BaseRule
func (br *BaseRule) baseUpdate(rule HostnameRule, category string, oldhostname string, params map[string]interface{}) (string, error) {
// Generate the new hostname using the passed rule's Generate method
newHostname, paramsJSON, err := rule.Generate(params)
2024-01-17 18:05:55 +01:00
if err != nil {
return "", err
2024-01-17 18:05:55 +01:00
}
// Update the hostname in the database
err = db.UpdateHostname(category, oldhostname, newHostname, paramsJSON)
2024-01-17 18:05:55 +01:00
if err != nil {
log.Printf("Error updating hostname in DB: %v", err)
return "", err
2024-01-17 18:05:55 +01:00
}
return newHostname, nil
2024-01-17 18:05:55 +01:00
}