cache and stats

This commit is contained in:
Aleksandr Trushkin
2024-02-04 21:40:37 +03:00
parent 08be7de118
commit 5d5e152429
2 changed files with 52 additions and 5 deletions

View File

@ -103,6 +103,10 @@ func (c *goodsItemClient) ListIter(
func (c *goodsItemClient) List(
ctx context.Context,
) (out []entity.GoodsItem, err error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
err = c.db.View(func(txn *badger.Txn) error {
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = true
@ -113,6 +117,10 @@ func (c *goodsItemClient) List(
prefix := c.prefix()
var cursor int
for iter.Seek(prefix); iter.ValidForPrefix(prefix); iter.Next() {
if ctx.Err() != nil {
return ctx.Err()
}
cursor++
current := iter.Item()
err = current.Value(func(val []byte) error {
@ -144,6 +152,10 @@ func (c *goodsItemClient) Get(
ctx context.Context,
sku string,
) (out entity.GoodsItem, err error) {
if ctx.Err() != nil {
return out, ctx.Err()
}
err = c.db.View(func(txn *badger.Txn) error {
key := unsafe.Slice(unsafe.StringData(sku), len(sku))
out, err = c.getBySKU(key, txn)
@ -161,6 +173,10 @@ func (c *goodsItemClient) Get(
}
func (c *goodsItemClient) GetByCart(ctx context.Context, id int64) (out entity.GoodsItem, err error) {
if ctx.Err() != nil {
return out, ctx.Err()
}
err = c.db.View(func(txn *badger.Txn) error {
idxKey := c.prefixedIDByCartInt64(id)
skuByCartIDItem, err := txn.Get(idxKey)
@ -196,6 +212,10 @@ func (c *goodsItemClient) UpsertMany(ctx context.Context, items ...entity.GoodsI
}
func (c *goodsItemClient) Delete(ctx context.Context, sku string) (out entity.GoodsItem, err error) {
if ctx.Err() != nil {
return out, ctx.Err()
}
err = c.db.Update(func(txn *badger.Txn) error {
skuKey := c.prefixedStr(sku)
out, err = c.getBySKU(skuKey, txn)
@ -208,6 +228,12 @@ func (c *goodsItemClient) Delete(ctx context.Context, sku string) (out entity.Go
return fmt.Errorf("deleting key: %w", err)
}
cartID := c.prefixedIDByCartInt64(out.Cart)
err = txn.Delete(cartID)
if err != nil {
return fmt.Errorf("deleting index key: %w", err)
}
return nil
})
if err != nil {
@ -223,10 +249,8 @@ func (c *goodsItemClient) upsertByBatch(ctx context.Context, items []entity.Good
err := func() error {
for _, item := range items {
select {
case <-ctx.Done():
if ctx.Err() != nil {
return ctx.Err()
default:
}
key := c.prefixedStr(item.Articul)