diff --git a/client.go b/client.go index 683660fa..0bffd360 100644 --- a/client.go +++ b/client.go @@ -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) diff --git a/client_test.go b/client_test.go index 9cea5e3c..14225311 100644 --- a/client_test.go +++ b/client_test.go @@ -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) +}