aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/controller/article.go
blob: 94735f19d598ed4090973bcc8086dc1d280777a1 (plain)
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
package controller

import (
	"errors"
	"projecty/cmd/web/model"
	"projecty/internal/authentication"
	"projecty/internal/database"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"
)

func ArticleDetailPage(c *fiber.Ctx) error {

	var article model.Article
	var authenticatedUser model.User
	isSelf := false
	isFollowed := false

	isAuthenticated, userID := authentication.AuthGet(c)

	db := database.Get()

	err := db.Model(&article).
		Where("slug = ?", c.Params("slug")).
		Preload("Favorites").
		Preload("Tags", func(db *gorm.DB) *gorm.DB {
			return db.Order("tags.name asc")
		}).
		Preload("User.Followers").
		Find(&article).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return c.Redirect("/")
		}
	}

	if isAuthenticated {
		db.Model(&authenticatedUser).
			Where("id = ?", userID).
			First(&authenticatedUser)
	}

	if isAuthenticated && article.User.FollowedBy(userID) {
		isFollowed = true
	}

	if isAuthenticated && article.User.ID == userID {
		isSelf = true
	}

	return c.Render("articles/show", fiber.Map{
		"PageTitle":          article.Title + " — Projecty",
		"Article":            article,
		"FiberCtx":           c,
		"IsOob":              false,
		"IsSelf":             isSelf,
		"IsFollowed":         isFollowed,
		"IsArticleFavorited": article.FavoritedBy(userID),
		"AuthenticatedUser":  authenticatedUser,
	}, "layouts/app")
}