Skip to content

Commit

Permalink
[GUILD-314] Add find with filter method
Browse files Browse the repository at this point in the history
  • Loading branch information
mcarriere committed Jan 22, 2019
1 parent 4f5a3d0 commit 64a6d57
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
22 changes: 22 additions & 0 deletions repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,28 @@ func (r *Repo) FindAll(ctx context.Context) ([]eh.Entity, error) {
return result, nil
}

// FindWithFilter allows to find entities with a filter
func (r *Repo) FindWithFilter(ctx context.Context, expr string, args ...interface{}) ([]eh.Entity, error) {
if r.factoryFn == nil {
return nil, eh.RepoError{
Err: ErrModelNotSet,
Namespace: eh.NamespaceFromContext(ctx),
}
}

table := r.service.Table(r.config.TableName)

iter := table.Scan().Filter(expr, args...).Consistent(true).Iter()
result := []eh.Entity{}
entity := r.factoryFn()
for iter.Next(entity) {
result = append(result, entity)
entity = r.factoryFn()
}

return result, nil
}

// Save implements the Save method of the eventhorizon.WriteRepo interface.
func (r *Repo) Save(ctx context.Context, entity eh.Entity) error {
table := r.service.Table(r.config.TableName)
Expand Down
21 changes: 19 additions & 2 deletions repo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,22 @@ func (suite *RepoTestSuite) TestSaveAndFindAll() {
assert.Equal(suite.T(), 2, len(results))
}

func (suite *RepoTestSuite) TestSaveAndFindWithFilter() {
testModel := &TestModel{ID: uuid.New(), Content: "test", FilterableID: 123}
testModel2 := &TestModel{ID: uuid.New(), Content: "test2", FilterableID: 123}
testModel3 := &TestModel{ID: uuid.New(), Content: "test3", FilterableID: 456}

err := suite.repo.Save(context.Background(), testModel)
suite.repo.Save(context.Background(), testModel2)
suite.repo.Save(context.Background(), testModel3)

results, err := suite.repo.FindWithFilter(context.Background(), "FilterableID = ?", 123)
if err != nil {
suite.T().Fatal("error finding entity:", err)
}
assert.Equal(suite.T(), 2, len(results))
}

func (suite *RepoTestSuite) TestRemove() {
testModel := &TestModel{ID: uuid.New(), Content: "test"}

Expand Down Expand Up @@ -177,8 +193,9 @@ func (suite *RepoTestSuite) TestParent() {
}

type TestModel struct {
ID uuid.UUID `dynamo:",hash"`
Content string
ID uuid.UUID `dynamo:",hash"`
Content string
FilterableID int
}

// EntityID implements the EntityID method of the eventhorizon.Entity interface.
Expand Down

0 comments on commit 64a6d57

Please sign in to comment.