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 }) }) }