diff --git a/rules/interface.go b/rules/interface.go index f79885f..0ec904a 100644 --- a/rules/interface.go +++ b/rules/interface.go @@ -9,41 +9,53 @@ import ( type HostnameRule interface { Generate(params map[string]interface{}) (string, []byte, error) - Insert(category string, hostname string, paramsJSON []byte) error - Update(category string, oldhostname string, hostname string, paramsJSON []byte) error + Insert(category string, params map[string]interface{}) (string, error) + Update(category string, oldhostname string, params map[string]interface{}) (string, error) } type BaseRule struct{} -func (br *BaseRule) baseInsert(category string, hostname string, paramsJSON []byte) error { +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 + } + exists, err := db.HostnameExists(category, hostname) if err != nil { - return fmt.Errorf("error checking existence of hostname: %v", err.Error()) + log.Printf("error checking existence of hostname: %v", err) + return "", err } if exists { - return fmt.Errorf("hostname %s does not exist in category %s", hostname, category) + log.Printf("hostname %s does not exist in category %s", hostname, category) + return "", fmt.Errorf("hostname-exists") } + + // Insert the hostname into the database err = db.InsertHostname(category, hostname, paramsJSON) if err != nil { log.Printf("Error inserting hostname into DB: %v", err) - return err - } - return nil -} - -func (br *BaseRule) baseUpdate(category string, oldhostname string, hostname string, paramsJSON []byte) error { - exists, err := db.HostnameExists(category, oldhostname) - if err != nil { - return fmt.Errorf("error checking existence of hostname: %v", err.Error()) - } - if !exists { - return fmt.Errorf("hostname %s does not exist in category %s", oldhostname, category) + return "", err } - err = db.UpdateHostname(category, oldhostname, hostname, paramsJSON) - if err != nil { - log.Printf("Error inserting hostname into DB: %v", err) - return err - } - return nil + return hostname, nil +} + +// 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) + if err != nil { + return "", err + } + + // Update the hostname in the database + err = db.UpdateHostname(category, oldhostname, newHostname, paramsJSON) + if err != nil { + log.Printf("Error updating hostname in DB: %v", err) + return "", err + } + + return newHostname, nil }