From ee95a54219382d653a57c103f91ae6188c484577 Mon Sep 17 00:00:00 2001 From: Andrew Starr-Bochicchio Date: Tue, 12 Jul 2022 12:06:33 -0400 Subject: [PATCH] droplets: Support listing Droplets filtered by name. (#541) --- droplets.go | 13 +++++++++++++ droplets_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/droplets.go b/droplets.go index 9a48456..5f19863 100644 --- a/droplets.go +++ b/droplets.go @@ -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) diff --git a/droplets_test.go b/droplets_test.go index 4e9e16c..17a62d7 100644 --- a/droplets_test.go +++ b/droplets_test.go @@ -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()