droplets: Support listing Droplets filtered by name. (#541)

This commit is contained in:
Andrew Starr-Bochicchio 2022-07-12 12:06:33 -04:00 committed by GitHub
parent f195ef76ef
commit ee95a54219
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -17,6 +17,7 @@ var errNoNetworks = errors.New("no networks have been defined")
// See: https://docs.digitalocean.com/reference/api/api-reference/#tag/Droplets
type DropletsService interface {
List(context.Context, *ListOptions) ([]Droplet, *Response, error)
ListByName(context.Context, string, *ListOptions) ([]Droplet, *Response, error)
ListByTag(context.Context, string, *ListOptions) ([]Droplet, *Response, error)
Get(context.Context, int) (*Droplet, *Response, error)
Create(context.Context, *DropletCreateRequest) (*Droplet, *Response, error)
@ -320,6 +321,18 @@ func (s *DropletsServiceOp) List(ctx context.Context, opt *ListOptions) ([]Dropl
return s.list(ctx, path)
}
// ListByName lists all Droplets filtered by name returning only exact matches.
// It is case-insensitive
func (s *DropletsServiceOp) ListByName(ctx context.Context, name string, opt *ListOptions) ([]Droplet, *Response, error) {
path := fmt.Sprintf("%s?name=%s", dropletBasePath, name)
path, err := addOptions(path, opt)
if err != nil {
return nil, nil, err
}
return s.list(ctx, path)
}
// ListByTag lists all Droplets matched by a Tag.
func (s *DropletsServiceOp) ListByTag(ctx context.Context, tag string, opt *ListOptions) ([]Droplet, *Response, error) {
path := fmt.Sprintf("%s?tag_name=%s", dropletBasePath, tag)

View File

@ -84,6 +84,45 @@ func TestDroplets_ListDropletsByTag(t *testing.T) {
}
}
func TestDroplets_ListDropletsByName(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/v2/droplets", func(w http.ResponseWriter, r *http.Request) {
name := "testing"
if r.URL.Query().Get("name") != name {
t.Errorf("Droplets.ListByName request did not contain the 'name=%s' query parameter", name)
}
testMethod(t, r, http.MethodGet)
fmt.Fprint(w, `{
"droplets": [
{
"id": 1,
"name": "testing"
},
{
"id": 2,
"name": "testing"
}
],
"meta": {
"total": 2
}
}`)
})
droplets, _, err := client.Droplets.ListByName(ctx, "testing", nil)
if err != nil {
t.Errorf("Droplets.ListByTag returned error: %v", err)
}
expected := []Droplet{{ID: 1, Name: "testing"}, {ID: 2, Name: "testing"}}
if !reflect.DeepEqual(droplets, expected) {
t.Errorf("Droplets.ListByTag returned droplets %+v, expected %+v", droplets, expected)
}
}
func TestDroplets_ListDropletsMultiplePages(t *testing.T) {
setup()
defer teardown()