owl-blogs/web/editor_handler.go

87 lines
1.8 KiB
Go
Raw Normal View History

2023-06-25 19:32:36 +00:00
package web
import (
"owl-blogs/app"
2023-07-17 18:44:59 +00:00
"owl-blogs/app/repository"
2023-06-25 20:09:27 +00:00
"owl-blogs/domain/model"
2023-07-16 19:48:39 +00:00
"owl-blogs/render"
2023-06-25 20:09:27 +00:00
"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 {
configRepo repository.ConfigRepository
2023-07-17 18:44:59 +00:00
entrySvc *app.EntryService
binSvc *app.BinaryService
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,
configRepo repository.ConfigRepository,
2023-07-08 11:28:06 +00:00
) *EditorHandler {
return &EditorHandler{
2023-07-17 18:44:59 +00:00
entrySvc: entryService,
registry: registry,
binSvc: binService,
configRepo: configRepo,
2023-07-08 11:28:06 +00:00
}
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
}
return render.RenderTemplateWithBase(c, getSiteConfig(h.configRepo), "views/editor", 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-09 20:12:06 +00:00
entry.SetPublishedAt(&now)
2023-07-13 19:55:08 +00:00
entry.SetAuthorId(c.Locals("author").(string))
2023-07-09 20:12:06 +00:00
err = h.entrySvc.Create(entry)
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
}