hostname-service/rules/notebook.go

94 lines
2.8 KiB
Go
Raw Normal View History

2024-01-17 18:05:55 +01:00
package rules
import (
"encoding/json"
"errors"
"fmt"
"log"
"git.beisel.it/florian/hostname-service/db"
// other imports if necessary
)
type NotebookRule struct {
BaseRule
OrgUnit string `json:"OrgUnit"`
Location string `json:"Location"`
Number int `json:"Number"`
}
type NotebookRuleInput struct {
OrgUnit string `json:"OrgUnit"`
Location string `json:"Location"`
}
// Ensure that NotebookRule implements HostnameRule interface
var _ HostnameRule = &NotebookRule{}
func (nr *NotebookRule) Generate(params map[string]interface{}) (string, []byte, error) {
var ok bool
// Get the orgUnit (IDE)
if nr.OrgUnit, ok = params["OrgUnit"].(string); !ok {
return "", nil, errors.New("OrgUnit parameter is required and must be a string")
}
// Get the location (HEN)
if nr.Location, ok = params["Location"].(string); !ok {
return "", nil, errors.New("location parameter is required and must be a string")
}
// Get last used number from the database and increment it
maxNumber, err := db.GetMaxNumberForCategory("notebook")
if err != nil {
return "", nil, err
}
newNumber := 1
if maxNumber >= 1 {
newNumber = int(maxNumber) + 1
}
nr.Number = newNumber
// Generate the hostname (orgUnit + Location + "NB" + Number)
hostname := fmt.Sprintf("%s%sNB%04d", nr.OrgUnit, nr.Location, nr.Number)
// Store the generated hostname in the database
// JSON parameters can be stored by marshalling the params map
paramsJSON, err := json.Marshal(nr)
if err != nil {
log.Printf("Error converting Category Struct to JSON: %v", err)
return "", nil, err
}
// Return the generated hostname and marshaled parameters
return hostname, paramsJSON, nil
}
// @Summary Generate hostname for category "notebook"
// @Description Generates a hostname for a notebook based on dynamic rules.
// @ID insert-notebook-hostname
// @Accept json
// @Produce json
// @Tags Generating Hostnames
// @Param body body NotebookRuleInput true "Input data to generate hostname"
// @Success 200 {string} string "Hostname"
// @Router /api/notebook [post]
func (nr *NotebookRule) Insert(category string, hostname string, paramsJSON []byte) error {
return nr.baseInsert(category, hostname, paramsJSON)
}
// @Summary Update hostname for category "notebook"
// @Description Generates a new hostname for a notebook based on dynamic rules.
// @ID update-notebook-hostname
// @Accept json
// @Produce json
// @Tags Generating Hostnames
// @Param body body NotebookRuleInput true "Input data to generate hostname"
// @Success 200 {string} string "Hostname"
// @Router /api/notebook [put]
func (nr *NotebookRule) Update(category string, oldhostname string, hostname string, paramsJSON []byte) error {
return nr.baseUpdate(category, oldhostname, hostname, paramsJSON)
}