datasource.mock.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. type FieldsDefinition = {
  2. name: string;
  3. // String type, usually something like 'string' or 'float'.
  4. type: string;
  5. };
  6. type Measurements = { [measurement: string]: FieldsDefinition[] };
  7. type FieldReturnValue = { text: string };
  8. /**
  9. * Datasource mock for influx. At the moment this only works for queries that should return measurements or their
  10. * fields and no other functionality is implemented.
  11. */
  12. export class InfluxDatasourceMock {
  13. constructor(private measurements: Measurements) {}
  14. metricFindQuery(query: string) {
  15. if (isMeasurementsQuery(query)) {
  16. return this.getMeasurements();
  17. } else {
  18. return this.getMeasurementFields(query);
  19. }
  20. }
  21. private getMeasurements(): FieldReturnValue[] {
  22. return Object.keys(this.measurements).map((key) => ({ text: key }));
  23. }
  24. private getMeasurementFields(query: string): FieldReturnValue[] {
  25. const match = query.match(/SHOW FIELD KEYS FROM \"(.+)\"/);
  26. if (!match) {
  27. throw new Error(`Failed to match query="${query}"`);
  28. }
  29. const measurementName = match[1];
  30. if (!measurementName) {
  31. throw new Error(`Failed to match measurement name from query="${query}"`);
  32. }
  33. const fields = this.measurements[measurementName];
  34. if (!fields) {
  35. throw new Error(
  36. `Failed to find measurement with name="${measurementName}" in measurements="[${Object.keys(
  37. this.measurements
  38. ).join(', ')}]"`
  39. );
  40. }
  41. return fields.map((field) => ({
  42. text: field.name,
  43. }));
  44. }
  45. }
  46. function isMeasurementsQuery(query: string) {
  47. return /SHOW MEASUREMENTS/.test(query);
  48. }