aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/model/article.go
blob: 1475a0ccf76c524bdc91fb6e502d68aa7490085a (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
package model

import (
	"gorm.io/gorm"
)

type Article struct {
	gorm.Model
	Slug        string `gorm:"uniqueIndex;not null"`
	Title       string `gorm:"not null" validate:"required"`
	Description string `validate:"required"`
	Body        string `validate:"required"`
	User        User   `validate:"-"`
	UserID      uint
	Comments    []Comment
	Favorites   []User `gorm:"many2many:article_favorite;"`
	Tags        []Tag  `gorm:"many2many:article_tag;"`
	IsFavorited bool   `gorm:"-"`
}

func (Article Article) GetFormattedCreatedAt() string {
	dateLayout := "Jan 02, 2006"
	return Article.CreatedAt.Format(dateLayout)
}

func (Article Article) GetFavoriteCount() int {
	return len(Article.Favorites)
}

func (Article Article) FavoritedBy(id uint) bool {
	if Article.Favorites == nil {
		return false
	}

	for _, u := range Article.Favorites {
		if u.ID == id {
			return true
		}
	}

	return false
}

func (Article Article) GetTagsAsCommaSeparated() string {
	tagsText := ""

	for i := 0; i < len(Article.Tags); i++ {
		tagsText += Article.Tags[i].Name + ","
	}

	return tagsText
}