owl-blogs/web/admin_handler.go

102 lines
2.1 KiB
Go
Raw Normal View History

2023-07-22 19:12:53 +00:00
package web
import (
"owl-blogs/app"
"owl-blogs/app/repository"
"owl-blogs/render"
2023-07-27 19:18:09 +00:00
"sort"
2023-07-22 19:12:53 +00:00
"github.com/gofiber/fiber/v2"
)
type adminHandler struct {
configRepo repository.ConfigRepository
configRegister *app.ConfigRegister
2023-07-27 19:18:09 +00:00
typeRegistry *app.EntryTypeRegistry
2024-02-21 19:03:18 +00:00
binSvc *app.BinaryService
2023-07-22 19:12:53 +00:00
}
2023-07-27 19:18:09 +00:00
type adminContet struct {
Configs []app.RegisteredConfig
Types []string
}
func NewAdminHandler(
configRepo repository.ConfigRepository,
configRegister *app.ConfigRegister,
typeRegistry *app.EntryTypeRegistry,
) *adminHandler {
2023-07-22 19:12:53 +00:00
return &adminHandler{
configRepo: configRepo,
configRegister: configRegister,
2023-07-27 19:18:09 +00:00
typeRegistry: typeRegistry,
2023-07-22 19:12:53 +00:00
}
}
func (h *adminHandler) Handle(c *fiber.Ctx) error {
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
configs := h.configRegister.Configs()
2023-07-27 19:18:09 +00:00
types := h.typeRegistry.Types()
typeNames := []string{}
for _, t := range types {
name, _ := h.typeRegistry.TypeName(t)
typeNames = append(typeNames, name)
}
// sort names to have a consistent order
sort.Slice(typeNames, func(i, j int) bool {
return typeNames[i] < typeNames[j]
})
return render.RenderTemplateWithBase(
c, "views/admin", &adminContet{
2023-07-27 19:18:09 +00:00
Configs: configs,
Types: typeNames,
},
)
2023-07-22 19:12:53 +00:00
}
func (h *adminHandler) HandleConfigGet(c *fiber.Ctx) error {
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
configName := c.Params("config")
config := h.configRegister.GetConfig(configName)
if config == nil {
return c.SendStatus(404)
}
err := h.configRepo.Get(configName, config)
if err != nil {
return err
}
2024-02-21 19:03:18 +00:00
htmlForm := config.Form(h.binSvc)
2023-07-22 19:12:53 +00:00
if err != nil {
return err
}
return render.RenderTemplateWithBase(c, "views/admin_config", htmlForm)
2023-07-22 19:12:53 +00:00
}
func (h *adminHandler) HandleConfigPost(c *fiber.Ctx) error {
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
configName := c.Params("config")
config := h.configRegister.GetConfig(configName)
if config == nil {
return c.SendStatus(404)
}
2024-02-21 19:24:18 +00:00
err := config.ParseFormData(c, h.binSvc)
2023-07-22 19:12:53 +00:00
if err != nil {
return err
}
2024-02-21 19:24:18 +00:00
h.configRepo.Update(configName, config)
2023-07-22 19:12:53 +00:00
return c.Redirect("")
}