diff options
Diffstat (limited to 'cmd/web/controller/htmx/home-action.go')
-rw-r--r-- | cmd/web/controller/htmx/home-action.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/cmd/web/controller/htmx/home-action.go b/cmd/web/controller/htmx/home-action.go new file mode 100644 index 0000000..5c4b872 --- /dev/null +++ b/cmd/web/controller/htmx/home-action.go @@ -0,0 +1,53 @@ +package HTMXController + +import ( + "errors" + "projecty/cmd/web/model" + "projecty/internal/authentication" + "projecty/internal/database" + "projecty/internal/helper" + + "github.com/gofiber/fiber/v2" + "gorm.io/gorm" +) + +func HomeFavoriteAction(c *fiber.Ctx) error { + + var article model.Article + var authenticatedUser model.User + + isArticleFavorited := false + + isAuthenticated, userID := authentication.AuthGet(c) + if !isAuthenticated { + return helper.HTMXRedirectTo("/sign-in", "/htmx/sign-in", c) + } + + db := database.Get() + + err := db.Model(&article). + Where("slug = ?", c.Params("slug")). + Preload("Favorites"). + Find(&article).Error + + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return helper.HTMXRedirectTo("/sign-in", "/htmx/sign-in", c) + } + } + + authenticatedUser.ID = userID + + if article.FavoritedBy(userID) { + db.Model(&article).Association("Favorites").Delete(&authenticatedUser) + } else { + db.Model(&article).Association("Favorites").Append(&authenticatedUser) + isArticleFavorited = true + } + + return c.Render("home/partials/article-favorite-button", fiber.Map{ + "GetFavoriteCount": article.GetFavoriteCount(), + "Slug": article.Slug, + "IsFavorited": isArticleFavorited, + }, "layouts/app-htmx") +} |