owl-blogs/web/admin_handler.go

105 lines
2.2 KiB
Go
Raw Permalink 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)
siteConfig := getSiteConfig(h.configRepo)
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, siteConfig,
"views/admin", &adminContet{
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
}
siteConfig := getSiteConfig(h.configRepo)
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, siteConfig, "views/admin_config", htmlForm)
}
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:03:18 +00:00
newConfig, err := config.ParseFormData(c, h.binSvc)
2023-07-22 19:12:53 +00:00
if err != nil {
return err
}
h.configRepo.Update(configName, newConfig)
return c.Redirect("")
}