1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
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 ArticleFavoriteAction(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("articles/partials/favorite-button", fiber.Map{
"Article": article,
"Slug": article.Slug,
"IsArticleFavorited": isArticleFavorited,
"IsOob": true,
}, "layouts/app-htmx")
}
func ArticleFollowAction(c *fiber.Ctx) error {
var article model.Article
var authenticatedUser model.User
isFollowed := 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").
Preload("User.Followers").
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.User.FollowedBy(userID) {
f := model.Follow{
FollowerID: article.UserID,
FollowingID: userID,
}
db.Model(&article.User).Association("Followers").Find(&f)
db.Delete(&f)
} else {
db.Model(&article.User).Association("Followers").Append(&model.Follow{FollowerID: article.UserID, FollowingID: userID})
isFollowed = true
}
return c.Render("articles/partials/follow-button", fiber.Map{
"Article": article,
"IsFollowed": isFollowed,
"IsOob": true,
}, "layouts/app-htmx")
}
|