owl-blogs/web/editor_handler.go

79 lines
1.5 KiB
Go
Raw Normal View History

2023-06-25 19:32:36 +00:00
package web
import (
"owl-blogs/app"
2023-06-25 20:09:27 +00:00
"owl-blogs/domain/model"
"owl-blogs/web/editor"
2023-07-06 17:36:24 +00:00
"time"
2023-06-25 19:32:36 +00:00
"github.com/gofiber/fiber/v2"
)
type EditorHandler struct {
entrySvc *app.EntryService
2023-07-08 10:03:10 +00:00
binSvc *app.BinaryService
2023-07-06 20:16:52 +00:00
registry *app.EntryTypeRegistry
2023-06-25 19:32:36 +00:00
}
2023-07-08 11:28:06 +00:00
func NewEditorHandler(
entryService *app.EntryService,
registry *app.EntryTypeRegistry,
binService *app.BinaryService,
) *EditorHandler {
return &EditorHandler{
entrySvc: entryService,
registry: registry,
binSvc: binService,
}
2023-07-06 20:16:52 +00:00
}
func (h *EditorHandler) paramToEntry(c *fiber.Ctx) (model.Entry, error) {
typeName := c.Params("editor")
entryType, err := h.registry.Type(typeName)
if err != nil {
return nil, err
}
return entryType, nil
2023-06-25 19:32:36 +00:00
}
func (h *EditorHandler) HandleGet(c *fiber.Ctx) error {
2023-07-05 20:03:00 +00:00
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
2023-07-06 20:16:52 +00:00
entryType, err := h.paramToEntry(c)
if err != nil {
return err
}
2023-07-08 10:03:10 +00:00
form := editor.NewEntryForm(entryType, h.binSvc)
2023-07-06 17:36:24 +00:00
htmlForm, err := form.HtmlForm()
2023-07-06 16:56:43 +00:00
if err != nil {
return err
}
2023-07-06 17:36:24 +00:00
return c.SendString(htmlForm)
2023-06-25 19:32:36 +00:00
}
func (h *EditorHandler) HandlePost(c *fiber.Ctx) error {
2023-07-05 20:03:00 +00:00
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
2023-07-06 17:36:24 +00:00
2023-07-06 20:16:52 +00:00
entryType, err := h.paramToEntry(c)
if err != nil {
return err
}
2023-07-08 10:03:10 +00:00
form := editor.NewEntryForm(entryType, h.binSvc)
2023-07-06 17:36:24 +00:00
// get form data
2023-07-07 19:04:25 +00:00
entry, err := form.Parse(c)
2023-07-06 17:36:24 +00:00
if err != nil {
return err
}
// create entry
now := time.Now()
2023-07-07 19:04:25 +00:00
err = h.entrySvc.Create(entry, &now, entry.MetaData())
2023-07-06 17:36:24 +00:00
if err != nil {
return err
}
2023-07-07 19:04:25 +00:00
return c.Redirect("/posts/" + entry.ID() + "/")
2023-07-06 17:36:24 +00:00
2023-06-25 19:32:36 +00:00
}