Skip to content

Commit

Permalink
Merge pull request #7 from nirmata/add-querybyid
Browse files Browse the repository at this point in the history
Add `QueryByID` method to the client
  • Loading branch information
atulatnirmata authored Jul 12, 2023
2 parents a9e39a4 + 29ce524 commit dbea004
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions pkg/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ type Client interface {
// returned.
QueryByName(service Service, modelIndex, name string) (ID, Error)

// QueryById is a convinience method that queries a service collection to find
// an object by its 'id' attribute. If a matching object is found, its ID is
// returned.
QueryById(service Service, modelIndex, id string) (ID, Error)

// WaitForState queries a state and returns when it matches the specified value
// or maxTime is reached
WaitForState(id ID, fieldIndex string, value interface{}, maxTime time.Duration, msg string) Error
Expand Down Expand Up @@ -667,6 +672,32 @@ func (c *client) QueryByName(service Service, modelIndex, name string) (ID, Erro
return obj.ID(), nil
}

func (c *client) QueryById(service Service, modelIndex, id string) (ID, Error) {
opts := &GetOptions{}
opts.Filter = NewQuery().FieldEqualsValue("id", id)
opts.Fields = []string{"id", "name", "modelIndex", "service"}

objs, err := c.GetCollection(service, modelIndex, opts)
if err != nil {
return nil, err
}

if len(objs) == 0 {
return nil, NewError("ErrorHTTP", fmt.Sprintf("HTTP: 404. Failed to find %s with id %s in service %s", modelIndex, id, service.Name()), nil)
}

if len(objs) > 1 {
return nil, NewError("ErrorInternal", fmt.Sprintf("Multiple %s instances with id %s in service %s", modelIndex, id, service.Name()), nil)
}

obj, newObjectErr := NewObject(objs[0])
if newObjectErr != nil {
return nil, NewError("ErrorInternal", "Failed to create object", newObjectErr)
}

return obj.ID(), nil
}

func (c *client) WaitForStates(id ID, fieldIndex string, values []interface{}, maxTime time.Duration, msg string) (interface{}, Error) {
timer := time.NewTimer(maxTime)
defer timer.Stop()
Expand Down

0 comments on commit dbea004

Please sign in to comment.