datasource.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. })
  22. .catch(error => {
  23. let message = 'Stackdriver: ';
  24. message += error.statusText ? error.statusText + ': ' : '';
  25. if (error.data && error.data.error && error.data.error.code) {
  26. // 400, 401
  27. message += error.data.error.code + '. ' + error.data.error.message;
  28. } else {
  29. message += 'Cannot connect to Stackdriver API';
  30. }
  31. return {
  32. status: 'error',
  33. message: message,
  34. };
  35. });
  36. }
  37. async getProjects() {
  38. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  39. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  40. }
  41. async doRequest(url, maxRetries = 1) {
  42. return this.backendSrv
  43. .datasourceRequest({
  44. url: this.url + url,
  45. method: 'GET',
  46. })
  47. .catch(error => {
  48. if (maxRetries > 0) {
  49. return this.doRequest(url, maxRetries - 1);
  50. }
  51. throw error;
  52. });
  53. }
  54. }