package repository import ( "encoding/json" "github.com/dgraph-io/badger/v4" "grow.rievo.dev/discordBots/cmd/dealsbot/api" "log" ) type Repository interface { GetAll() ([]api.Deal, error) GetValue(dealId string) api.Deal SetValue(deal api.Deal) error DeleteValue(dealId string) error Close() error } type DealRepository struct { db *badger.DB } func InitDb() *DealRepository { opts := badger.DefaultOptions("./db") opts.Logger = nil db, err := badger.Open(opts) if err != nil { log.Fatal(err) } return &DealRepository{db} } func (d *DealRepository) Close() error { return d.db.Close() } func (d *DealRepository) RunGC() error { return d.db.RunValueLogGC(0.7) } func (d *DealRepository) GetAll() ([]api.Deal, error) { var deals []api.Deal err := d.db.View(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions opts.PrefetchSize = 10 it := txn.NewIterator(opts) defer it.Close() for it.Rewind(); it.Valid(); it.Next() { item := it.Item() err := item.Value(func(val []byte) error { retrievedDeal := api.Deal{} err := json.Unmarshal(val, &retrievedDeal) deals = append(deals, retrievedDeal) return err }) if err != nil { return err } } return nil }) return deals, err } func (d *DealRepository) GetValue(dealId string) (api.Deal, error) { retrievedDeal := api.Deal{} err := d.db.View(func(txn *badger.Txn) error { item, err := txn.Get([]byte(dealId)) if err != nil { return err } err = item.Value(func(val []byte) error { err = json.Unmarshal(val, &retrievedDeal) return err }) return err }) if err != nil { return api.Deal{}, err } return retrievedDeal, nil } func (d *DealRepository) SetValue(deal api.Deal) error { jsonBytes, err := json.Marshal(deal) if err != nil { return err } err = d.db.Update(func(txn *badger.Txn) error { err := txn.Set([]byte(deal.Id), jsonBytes) return err }) if err != nil { return err } return nil } func (d *DealRepository) DeleteValue(dealId string) error { err := d.db.Update(func(txn *badger.Txn) error { err := txn.Delete([]byte(dealId)) return err }) return err } func (d *DealRepository) DeleteAll() error { err := d.db.Update(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions opts.PrefetchSize = 10 it := txn.NewIterator(opts) defer it.Close() for it.Rewind(); it.Valid(); it.Next() { item := it.Item() err := txn.Delete(item.Key()) if err != nil { return err } } return nil }) return err }