Skip to content

Commit 3a26594

Browse files
feat: add prepareIndexes() method to NewAdapterByDB() (#64)
* feat: go mod tidy * feat: create reuse able prepareIndexes function and apply to NewAdapterByDB and open functions
1 parent 8560937 commit 3a26594

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

adapter.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,13 +157,19 @@ func NewAdapterByDB(client *mongo.Client, config *AdapterConfig) (persist.BatchA
157157
config.Timeout = defaultTimeout
158158
}
159159

160+
collection := client.Database(config.DatabaseName).Collection(config.CollectionName)
161+
160162
a := &adapter{
161163
client: client,
162-
collection: client.Database(config.DatabaseName).Collection(config.CollectionName),
164+
collection: collection,
163165
timeout: config.Timeout,
164166
filtered: config.IsFiltered,
165167
}
166168

169+
if err := a.prepareIndexes(); err != nil {
170+
return nil, err
171+
}
172+
167173
// Call the destructor when the object is released.
168174
runtime.SetFinalizer(a, finalizer)
169175

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

194+
if err = a.prepareIndexes(); err != nil {
195+
return err
196+
}
197+
198+
return nil
199+
}
200+
201+
func (a *adapter) prepareIndexes() error {
188202
indexes := []string{"ptype", "v0", "v1", "v2", "v3", "v4", "v5"}
189203
keysDoc := bson.D{}
190204

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

198-
if _, err = collection.Indexes().CreateOne(
212+
if _, err := a.collection.Indexes().CreateOne(
199213
context.Background(),
200214
mongo.IndexModel{
201215
Keys: keysDoc,

go.mod

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,17 @@ require (
66
github.com/casbin/casbin/v2 v2.71.1
77
go.mongodb.org/mongo-driver v1.12.0
88
)
9+
10+
require (
11+
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible // indirect
12+
github.com/golang/snappy v0.0.1 // indirect
13+
github.com/klauspost/compress v1.13.6 // indirect
14+
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
15+
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
16+
github.com/xdg-go/scram v1.1.2 // indirect
17+
github.com/xdg-go/stringprep v1.0.4 // indirect
18+
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
19+
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
20+
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
21+
golang.org/x/text v0.7.0 // indirect
22+
)

0 commit comments

Comments
 (0)