datasource.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import _ from 'lodash';
  2. import TableModel from 'app/core/table_model';
  3. import { DataSourceApi, DataQueryOptions } from '@grafana/ui';
  4. import { TestDataQuery, Scenario } from './types';
  5. export class TestDataDatasource implements DataSourceApi<TestDataQuery> {
  6. id: number;
  7. /** @ngInject */
  8. constructor(instanceSettings, private backendSrv, private $q) {
  9. this.id = instanceSettings.id;
  10. }
  11. query(options: DataQueryOptions<TestDataQuery>) {
  12. const queries = _.filter(options.targets, item => {
  13. return item.hide !== true;
  14. }).map(item => {
  15. return {
  16. refId: item.refId,
  17. scenarioId: item.scenarioId,
  18. intervalMs: options.intervalMs,
  19. maxDataPoints: options.maxDataPoints,
  20. stringInput: item.stringInput,
  21. points: item.points,
  22. alias: item.alias,
  23. datasourceId: this.id,
  24. };
  25. });
  26. if (queries.length === 0) {
  27. return this.$q.when({ data: [] });
  28. }
  29. return this.backendSrv
  30. .datasourceRequest({
  31. method: 'POST',
  32. url: '/api/tsdb/query',
  33. data: {
  34. from: options.range.from.valueOf().toString(),
  35. to: options.range.to.valueOf().toString(),
  36. queries: queries,
  37. },
  38. })
  39. .then(res => {
  40. const data = [];
  41. if (res.data.results) {
  42. _.forEach(res.data.results, queryRes => {
  43. if (queryRes.tables) {
  44. for (const table of queryRes.tables) {
  45. const model = new TableModel();
  46. model.rows = table.rows;
  47. model.columns = table.columns;
  48. data.push(model);
  49. }
  50. }
  51. for (const series of queryRes.series) {
  52. data.push({
  53. target: series.name,
  54. datapoints: series.points,
  55. });
  56. }
  57. });
  58. }
  59. return { data: data };
  60. });
  61. }
  62. annotationQuery(options) {
  63. let timeWalker = options.range.from.valueOf();
  64. const to = options.range.to.valueOf();
  65. const events = [];
  66. const eventCount = 10;
  67. const step = (to - timeWalker) / eventCount;
  68. for (let i = 0; i < eventCount; i++) {
  69. events.push({
  70. annotation: options.annotation,
  71. time: timeWalker,
  72. text: 'This is the text, <a href="https://grafana.com">Grafana.com</a>',
  73. tags: ['text', 'server'],
  74. });
  75. timeWalker += step;
  76. }
  77. return this.$q.when(events);
  78. }
  79. testDatasource() {
  80. return Promise.resolve({
  81. status: 'success',
  82. message: 'Data source is working',
  83. });
  84. }
  85. getScenarios(): Promise<Scenario[]> {
  86. return this.backendSrv.get('/api/tsdb/testdata/scenarios');
  87. }
  88. }