@@ -4,6 +4,33 @@ const { URL, URLSearchParams } = require('url');
44
55/// <reference path="../types.d.ts"/>
66
7+ /**
8+ * If the given url does not have a host, it will add it to the
9+ * url and return it.
10+ * @param {string } url the url
11+ * @returns {string } the expanded URL.
12+ */
13+ function expandUrl ( url , host ) {
14+
15+ if ( url . startsWith ( 'http://' ) || url . startsWith ( 'https://' ) ) {
16+ return url ;
17+ }
18+
19+ if ( ! host ) {
20+ throw new Error ( 'No Grafana endpoint configured.' ) ;
21+ }
22+
23+ let apiUrl = host ;
24+ if ( ! apiUrl . endsWith ( '/' ) ) {
25+ apiUrl += '/' ;
26+ }
27+
28+ apiUrl += 'api/' ;
29+ apiUrl += url ;
30+
31+ return apiUrl ;
32+ }
33+
734class GrafanaClient {
835 /**
936 * Creates a new instance.
@@ -38,12 +65,7 @@ class GrafanaClient {
3865 * @returns {Promise<unknown> } the response data
3966 */
4067 async get ( url ) {
41- if ( ! url . startsWith ( 'http://' ) && ! url . startsWith ( 'https://' ) && ! this . host ) {
42- throw new Error ( 'No Grafana endpoint configured.' ) ;
43- }
44-
45- const fullUrl = url . startsWith ( 'http://' ) || url . startsWith ( 'https://' ) ? url : `${ this . host } /api/${ url } ` ;
46-
68+ const fullUrl = expandUrl ( url , this . host ) ;
4769 const response = await fetch ( fullUrl , {
4870 method : 'GET' ,
4971 headers : grafanaHeaders ( null , false , this . apiKey ) ,
@@ -63,8 +85,7 @@ class GrafanaClient {
6385 * @returns {Promise<unknown> }
6486 */
6587 async post ( url , data ) {
66- const fullUrl = url . startsWith ( 'http://' ) || url . startsWith ( 'https://' ) ? url : `${ this . host } /api/${ url } ` ;
67-
88+ const fullUrl = expandUrl ( url , this . host ) ;
6889 const response = await fetch ( fullUrl , {
6990 method : 'POST' ,
7091 headers : grafanaHeaders ( 'application/json' , false , this . apiKey ) ,
@@ -87,16 +108,27 @@ class GrafanaClient {
87108 return ;
88109 }
89110
90- if ( response . headers . get ( 'content-type' ) == 'application/json' ) {
91- const json = await response . json ( ) ;
111+ let contentType = null ;
112+ if ( response . headers . has ( 'content-type' ) ) {
113+ contentType = response . headers . get ( 'content-type' ) ;
114+ if ( contentType . includes ( ';' ) ) {
115+ contentType = contentType . split ( ';' ) [ 0 ] ;
116+ }
117+ }
92118
119+ if ( contentType == 'application/json' ) {
120+ const json = await response . json ( ) ;
93121 const error = new Error ( json . message || 'Error while fetching data from Grafana.' ) ;
94122 error . data = json ;
95123 throw error ;
96124 }
97125
98- const text = await response . text ( ) ;
99- throw new Error ( text ) ;
126+ let error = new Error ( 'Error while fetching data from Grafana.' ) ;
127+ if ( contentType != 'text/html' ) {
128+ error . data = await response . text ( ) ;
129+ }
130+
131+ throw error ;
100132 }
101133
102134 /**
0 commit comments