datasource.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /** @ngInject */
  2. export default class StackdriverDatasource {
  3. url: string;
  4. baseUrl: string;
  5. constructor(instanceSettings, private backendSrv) {
  6. this.baseUrl = `/stackdriver/`;
  7. this.url = instanceSettings.url;
  8. this.doRequest = this.doRequest;
  9. }
  10. testDatasource() {
  11. const path = `v3/projects/raintank-production/metricDescriptors`;
  12. return this.doRequest(`${this.baseUrl}${path}`)
  13. .then(response => {
  14. if (response.status === 200) {
  15. return {
  16. status: 'success',
  17. message: 'Successfully queried the Stackdriver API.',
  18. title: 'Success',
  19. };
  20. }
  21. return {
  22. status: 'error',
  23. message: 'Returned http status code ' + response.status,
  24. };
  25. })
  26. .catch(error => {
  27. let message = 'Stackdriver: ';
  28. message += error.statusText ? error.statusText + ': ' : '';
  29. if (error.data && error.data.error && error.data.error.code) {
  30. // 400, 401
  31. message += error.data.error.code + '. ' + error.data.error.message;
  32. } else {
  33. message += 'Cannot connect to Stackdriver API';
  34. }
  35. return {
  36. status: 'error',
  37. message: message,
  38. };
  39. });
  40. }
  41. async getProjects() {
  42. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  43. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  44. }
  45. async doRequest(url, maxRetries = 1) {
  46. return this.backendSrv
  47. .datasourceRequest({
  48. url: this.url + url,
  49. method: 'GET',
  50. })
  51. .catch(error => {
  52. if (maxRetries > 0) {
  53. return this.doRequest(url, maxRetries - 1);
  54. }
  55. throw error;
  56. });
  57. }
  58. }