datasource.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import _ from 'lodash';
  3. export class MysqlDatasource {
  4. id: any;
  5. name: any;
  6. /** @ngInject **/
  7. constructor(instanceSettings, private backendSrv, private $q, private templateSrv) {
  8. this.name = instanceSettings.name;
  9. this.id = instanceSettings.id;
  10. }
  11. interpolateVariable(value) {
  12. if (typeof value === 'string') {
  13. return '\"' + value + '\"';
  14. }
  15. var quotedValues = _.map(value, function(val) {
  16. return '\"' + val + '\"';
  17. });
  18. return quotedValues.join(',');
  19. }
  20. query(options) {
  21. var queries = _.filter(options.targets, item => {
  22. return item.hide !== true;
  23. }).map(item => {
  24. return {
  25. refId: item.refId,
  26. intervalMs: options.intervalMs,
  27. maxDataPoints: options.maxDataPoints,
  28. datasourceId: this.id,
  29. rawSql: this.templateSrv.replace(item.rawSql, options.scopedVars, this.interpolateVariable),
  30. format: item.format,
  31. };
  32. });
  33. if (queries.length === 0) {
  34. return this.$q.when({data: []});
  35. }
  36. return this.backendSrv.datasourceRequest({
  37. url: '/api/tsdb/query',
  38. method: 'POST',
  39. data: {
  40. from: options.range.from.valueOf().toString(),
  41. to: options.range.to.valueOf().toString(),
  42. queries: queries,
  43. }
  44. }).then(this.processQueryResult.bind(this));
  45. }
  46. processQueryResult(res) {
  47. var data = [];
  48. if (!res.data.results) {
  49. return {data: data};
  50. }
  51. for (let key in res.data.results) {
  52. let queryRes = res.data.results[key];
  53. if (queryRes.series) {
  54. for (let series of queryRes.series) {
  55. data.push({
  56. target: series.name,
  57. datapoints: series.points,
  58. refId: queryRes.refId,
  59. meta: queryRes.meta,
  60. });
  61. }
  62. }
  63. if (queryRes.tables) {
  64. for (let table of queryRes.tables) {
  65. table.type = 'table';
  66. table.refId = queryRes.refId;
  67. table.meta = queryRes.meta;
  68. data.push(table);
  69. }
  70. }
  71. }
  72. return {data: data};
  73. }
  74. }