Passed
Pull Request — master (#2516)
by Tolga
04:08
created

memory.NewBundleWriter   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
package memory
2
3
import (
4
	"context"
5
	"errors"
6
7
	"github.com/Permify/permify/internal/storage"
8
	"github.com/Permify/permify/internal/storage/memory/constants"
9
	db "github.com/Permify/permify/pkg/database/memory"
10
	base "github.com/Permify/permify/pkg/pb/base/v1"
11
)
12
13
// BundleWriter -
14
type BundleWriter struct {
15
	database *db.Memory
16
}
17
18
func NewBundleWriter(database *db.Memory) *BundleWriter {
19
	return &BundleWriter{
20
		database: database,
21
	}
22
}
23
24
func (b *BundleWriter) Write(ctx context.Context, bundles []storage.Bundle) (names []string, err error) {
25
	txn := b.database.DB.Txn(true)
26
	defer txn.Abort()
27
28
	for _, bundle := range bundles {
29
		if err = txn.Insert(constants.BundlesTable, bundle); err != nil {
30
			return []string{}, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
31
		}
32
		names = append(names, bundle.Name)
33
	}
34
	txn.Commit()
35
36
	return names, nil
37
}
38
39
func (b *BundleWriter) Delete(ctx context.Context, tenantID, name string) (err error) {
40
	txn := b.database.DB.Txn(true)
41
	raw, err := txn.First(constants.BundlesTable, "id", tenantID, name)
42
43
	if raw == nil {
44
		return errors.New(base.ErrorCode_ERROR_CODE_BUNDLE_NOT_FOUND.String())
45
	}
46
	err = txn.Delete(constants.BundlesTable, raw)
47
	if err != nil {
48
		return err
49
	}
50
	txn.Commit()
51
52
	return nil
53
}
54