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
|
package repository
import (
"encoding/json"
"fmt"
"strconv"
"time"
"gitrepo.ru/neonxp/gorum/models"
"go.etcd.io/bbolt"
)
type Post struct {
db *bbolt.DB
}
func NewPost(db *bbolt.DB) *Post {
return &Post{
db: db,
}
}
func (t *Post) CreatePost(
text string,
authorID string,
topicID uint64,
) (uint64, error) {
post := &models.Post{
Text: text,
AuthorID: authorID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
return post.ID, t.db.Update(func(tx *bbolt.Tx) error {
bucket, err := tx.CreateBucketIfNotExists([]byte(fmt.Sprintf("posts_%d", topicID)))
if err != nil {
return err
}
id, err := bucket.NextSequence()
if err != nil {
return err
}
post.ID = id
pb, err := json.Marshal(post)
if err != nil {
return err
}
return bucket.Put([]byte(strconv.Itoa(int(id))), pb)
})
}
func (t *Post) List(topicID uint64) ([]*models.Post, error) {
posts := make([]*models.Post, 0)
return posts, t.db.View(func(tx *bbolt.Tx) error {
return tx.Bucket([]byte(fmt.Sprintf("posts_%d", topicID))).ForEach(func(k, v []byte) error {
post := new(models.Post)
if err := json.Unmarshal(v, post); err != nil {
return err
}
posts = append(posts, post)
return nil
})
})
}
|