response_parser.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { AnnotationEvent, DataFrame, MetricFindValue } from '@grafana/data';
  2. import { BackendDataSourceResponse, toDataQueryResponse, FetchResponse } from '@grafana/runtime';
  3. export default class ResponseParser {
  4. transformMetricFindResponse(raw: FetchResponse<BackendDataSourceResponse>): MetricFindValue[] {
  5. const frames = toDataQueryResponse(raw).data as DataFrame[];
  6. if (!frames || !frames.length) {
  7. return [];
  8. }
  9. const frame = frames[0];
  10. const values: MetricFindValue[] = [];
  11. const textField = frame.fields.find((f) => f.name === '__text');
  12. const valueField = frame.fields.find((f) => f.name === '__value');
  13. if (textField && valueField) {
  14. for (let i = 0; i < textField.values.length; i++) {
  15. values.push({ text: '' + textField.values.get(i), value: '' + valueField.values.get(i) });
  16. }
  17. } else {
  18. values.push(
  19. ...frame.fields
  20. .flatMap((f) => f.values.toArray())
  21. .map((v) => ({
  22. text: v,
  23. }))
  24. );
  25. }
  26. return Array.from(new Set(values.map((v) => v.text))).map((text) => ({
  27. text,
  28. value: values.find((v) => v.text === text)?.value,
  29. }));
  30. }
  31. async transformAnnotationResponse(options: any, data: BackendDataSourceResponse): Promise<AnnotationEvent[]> {
  32. const frames = toDataQueryResponse({ data: data }).data as DataFrame[];
  33. if (!frames || !frames.length) {
  34. return [];
  35. }
  36. const frame = frames[0];
  37. const timeField = frame.fields.find((f) => f.name === 'time');
  38. if (!timeField) {
  39. return Promise.reject({ message: 'Missing mandatory time column (with time column alias) in annotation query.' });
  40. }
  41. const timeEndField = frame.fields.find((f) => f.name === 'timeend');
  42. const textField = frame.fields.find((f) => f.name === 'text');
  43. const tagsField = frame.fields.find((f) => f.name === 'tags');
  44. const list: AnnotationEvent[] = [];
  45. for (let i = 0; i < frame.length; i++) {
  46. const timeEnd = timeEndField && timeEndField.values.get(i) ? Math.floor(timeEndField.values.get(i)) : undefined;
  47. list.push({
  48. annotation: options.annotation,
  49. time: Math.floor(timeField.values.get(i)),
  50. timeEnd,
  51. text: textField && textField.values.get(i) ? textField.values.get(i) : '',
  52. tags:
  53. tagsField && tagsField.values.get(i)
  54. ? tagsField.values
  55. .get(i)
  56. .trim()
  57. .split(/\s*,\s*/)
  58. : [],
  59. });
  60. }
  61. return list;
  62. }
  63. }