Skip to content

Commit

Permalink
feat: add prepareIndexes() method to NewAdapterByDB() (#64)
Browse files Browse the repository at this point in the history
* feat: go mod tidy

* feat: create reuse able prepareIndexes function and apply to NewAdapterByDB and open functions
  • Loading branch information
toeydevelopment authored Jul 22, 2024
1 parent 8560937 commit 3a26594
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 16 additions & 2 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,19 @@ func NewAdapterByDB(client *mongo.Client, config *AdapterConfig) (persist.BatchA
config.Timeout = defaultTimeout
}

collection := client.Database(config.DatabaseName).Collection(config.CollectionName)

a := &adapter{
client: client,
collection: client.Database(config.DatabaseName).Collection(config.CollectionName),
collection: collection,
timeout: config.Timeout,
filtered: config.IsFiltered,
}

if err := a.prepareIndexes(); err != nil {
return nil, err
}

// Call the destructor when the object is released.
runtime.SetFinalizer(a, finalizer)

Expand All @@ -185,6 +191,14 @@ func (a *adapter) open(clientOption *options.ClientOptions, databaseName string,
a.client = client
a.collection = collection

if err = a.prepareIndexes(); err != nil {
return err
}

return nil
}

func (a *adapter) prepareIndexes() error {
indexes := []string{"ptype", "v0", "v1", "v2", "v3", "v4", "v5"}
keysDoc := bson.D{}

Expand All @@ -195,7 +209,7 @@ func (a *adapter) open(clientOption *options.ClientOptions, databaseName string,
keysDoc = append(keysDoc, keyDoc)
}

if _, err = collection.Indexes().CreateOne(
if _, err := a.collection.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: keysDoc,
Expand Down
14 changes: 14 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,17 @@ require (
github.com/casbin/casbin/v2 v2.71.1
go.mongodb.org/mongo-driver v1.12.0
)

require (
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/text v0.7.0 // indirect
)

0 comments on commit 3a26594

Please sign in to comment.