aboutsummaryrefslogtreecommitdiff
path: root/repository/topic.go
blob: 4c34643f177127363f74d8557688e49068eb3ee6 (plain) (blame)
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
package repository

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"gitrepo.ru/neonxp/gorum/models"
	"go.etcd.io/bbolt"
)

type Topic struct {
	db *bbolt.DB
}

func NewTopic(db *bbolt.DB) *Topic {
	return &Topic{
		db: db,
	}
}

func (t *Topic) Init() error {
	return t.db.Update(func(tx *bbolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte("topics"))
		return err
	})
}

func (t *Topic) Create(title, text, authorID string, parentID uint64) (*models.Topic, error) {
	topic := &models.Topic{
		Topic:     title,
		Text:      text,
		AuthorID:  authorID,
		ParentID:  parentID,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	return topic, t.db.Update(func(tx *bbolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists([]byte("topics"))
		if err != nil {
			return err
		}
		id, err := bucket.NextSequence()
		if err != nil {
			return err
		}
		topic.ID = id
		tb, err := json.Marshal(topic)
		if err != nil {
			return err
		}

		if _, err := tx.CreateBucketIfNotExists([]byte(fmt.Sprintf("posts_%d", topic.ID))); err != nil {
			return err
		}

		return bucket.Put([]byte(strconv.Itoa(int(topic.ID))), tb)
	})
}

func (t *Topic) List(parentID uint64) ([]*models.Topic, error) {
	topics := make([]*models.Topic, 0)

	return topics, t.db.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket([]byte("topics"))
		if bucket == nil {
			return models.ErrDBNotInitialized
		}

		return bucket.ForEach(func(k, v []byte) error {
			t := new(models.Topic)
			if err := json.Unmarshal(v, t); err != nil {
				return err
			}
			if t.ParentID == parentID {
				topics = append(topics, t)
			}

			return nil
		})
	})
}

func (t *Topic) Get(topicID uint64) (*models.Topic, error) {
	topic := new(models.Topic)

	return topic, t.db.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket([]byte("topics"))
		if bucket == nil {
			return models.ErrDBNotInitialized
		}
		tb := bucket.Get([]byte(strconv.Itoa(int(topicID))))
		if tb == nil {
			return models.ErrTopicNotFound
		}

		return json.Unmarshal(tb, topic)
	})
}