diff options
author | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-29 02:47:35 +0300 |
---|---|---|
committer | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-07-29 02:47:35 +0300 |
commit | 96e2ce2e9d363a6296f9411ecb00168520258874 (patch) | |
tree | 09aa7fffe10eab84ae0edd39e570355984ba0148 /repository/post.go | |
parent | 12ed72e4e1da181a6c87319a50d3b4142788b4c0 (diff) |
Отказ от echo
Diffstat (limited to 'repository/post.go')
-rw-r--r-- | repository/post.go | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/repository/post.go b/repository/post.go new file mode 100644 index 0000000..1b0fef6 --- /dev/null +++ b/repository/post.go @@ -0,0 +1,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 + }) + }) +} |