github.com/ngocphuongnb/tetua@v0.0.7-alpha/app/entities/topic.go (about) 1 package entities 2 3 import ( 4 "net/url" 5 "strings" 6 "time" 7 8 "github.com/ngocphuongnb/tetua/app/utils" 9 ) 10 11 // Topic is the model entity for the Topic schema. 12 type Topic struct { 13 ID int `json:"id,omitempty"` 14 CreatedAt *time.Time `json:"created_at,omitempty"` 15 UpdatedAt *time.Time `json:"updated_at,omitempty"` 16 DeletedAt *time.Time `json:"deleted_at,omitempty"` 17 Name string `json:"name,omitempty" validate:"max=255"` 18 Slug string `json:"slug,omitempty" validate:"max=255"` 19 Description string `json:"description,omitempty" validate:"max=255"` 20 Content string `json:"content,omitempty" validate:"required"` 21 ContentHTML string `json:"content_html,omitempty" validate:"required"` 22 ParentID int `json:"parent_id,omitempty"` 23 Parent *Topic `json:"parent,omitempty"` 24 Children []*Topic `json:"children,omitempty"` 25 Posts []*Post `json:"posts,omitempty"` 26 } 27 28 type TopicFilter struct { 29 *Filter 30 } 31 32 type TopicMutation struct { 33 ID int `form:"id" json:"id"` 34 Name string `form:"name" json:"name"` 35 Content string `form:"content" json:"content"` 36 ContentHTML string `json:"content_html,omitempty" validate:"required"` 37 ParentID int `form:"parent_id" json:"parent_id"` 38 } 39 40 func (t *Topic) Url() string { 41 return utils.Url(t.Slug) 42 } 43 44 func (t *Topic) FeedUrl() string { 45 return utils.Url(t.Slug + "/feed") 46 } 47 48 func GetTopicsTree(topics []*Topic, rootTopic, level int, ignore []int) []*Topic { 49 var result []*Topic 50 51 for _, topic := range topics { 52 if utils.SliceContains(ignore, topic.ID) { 53 continue 54 } 55 if topic.ParentID == rootTopic { 56 topic.Children = GetTopicsTree(topics, topic.ID, level+1, ignore) 57 result = append(result, topic) 58 } 59 } 60 61 return result 62 } 63 64 func topicTree(topics []*Topic, level int, ignore []int) []*Topic { 65 var result []*Topic 66 for _, topic := range topics { 67 if utils.SliceContains(ignore, topic.ID) { 68 continue 69 } 70 71 topic.Name = strings.Repeat("--", level) + topic.Name 72 result = append(result, topic) 73 74 if len(topic.Children) > 0 { 75 result = append(result, topicTree(topic.Children, level+1, ignore)...) 76 } 77 } 78 79 return result 80 } 81 82 func PrintTopicsTree(topics []*Topic, ignore []int) []*Topic { 83 ts := GetTopicsTree(topics, 0, 0, []int{}) 84 topics = topicTree(ts, 0, ignore) 85 return topics 86 } 87 88 func (p *TopicFilter) Base() string { 89 q := url.Values{} 90 if !utils.SliceContains(p.IgnoreUrlParams, "search") && p.Search != "" { 91 q.Add("q", p.Search) 92 } 93 94 if queryString := q.Encode(); queryString != "" { 95 return p.FilterBaseUrl() + "?" + q.Encode() 96 } 97 98 return p.FilterBaseUrl() 99 }