Skip to content

Commit

Permalink
Merge pull request #152 from K-Phoen/datasource-uid-by-name
Browse files Browse the repository at this point in the history
Add a utility function to get a datasource UID by its name
  • Loading branch information
K-Phoen authored Dec 24, 2021
2 parents c330423 + ec67740 commit aeb936a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
27 changes: 27 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,33 @@ func (client *Client) DeleteDatasource(ctx context.Context, name string) error {
return nil
}

// GetDatasourceUIDByName finds a datasource UID given its name.
func (client *Client) GetDatasourceUIDByName(ctx context.Context, name string) (string, error) {
resp, err := client.get(ctx, "/api/datasources/name/"+name)
if err != nil {
return "", err
}

defer func() { _ = resp.Body.Close() }()

if resp.StatusCode == http.StatusNotFound {
return "", ErrDatasourceNotFound
}

if resp.StatusCode != http.StatusOK {
return "", client.httpError(resp)
}

response := struct {
UID string `json:"uid"`
}{}
if err := decodeJSON(resp.Body, &response); err != nil {
return "", err
}

return response.UID, nil
}

// getDatasourceIDByName finds a datasource, given its name.
func (client *Client) getDatasourceIDByName(ctx context.Context, name string) (int, error) {
resp, err := client.get(ctx, "/api/datasources/id/"+name)
Expand Down
36 changes: 36 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,39 @@ func TestDeleteDatasourceForwardsErrorOnFailure(t *testing.T) {
req.Error(err)
req.Contains(err.Error(), "something when wrong")
}

func TestGetDatasourceUIDByName(t *testing.T) {
req := require.New(t)

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{
"uid": "some-uid"
}`)
}))
defer ts.Close()

client := NewClient(http.DefaultClient, ts.URL)

uid, err := client.GetDatasourceUIDByName(context.TODO(), "some-prometheus")

req.NoError(err)
req.Equal("some-uid", uid)
}

func TestGetDatasourceUIDByNameReturnsASpecificErrorIfDatasourceIsNotFound(t *testing.T) {
req := require.New(t)

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer ts.Close()

client := NewClient(http.DefaultClient, ts.URL)

uid, err := client.GetDatasourceUIDByName(context.TODO(), "some-prometheus")

req.Error(err)
req.Equal(ErrDatasourceNotFound, err)
req.Empty(uid)
}

0 comments on commit aeb936a

Please sign in to comment.