urlParser.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { isArray, isString } from 'lodash';
  2. import { UrlQueryValue } from '@grafana/data';
  3. import { AdHocVariableFilter } from 'app/features/variables/types';
  4. export const toUrl = (filters: AdHocVariableFilter[]): string[] => {
  5. return filters.map((filter) => toArray(filter).map(escapeDelimiter).join('|'));
  6. };
  7. export const toFilters = (value: UrlQueryValue): AdHocVariableFilter[] => {
  8. if (isArray(value)) {
  9. const values = value as any[];
  10. return values.map(toFilter).filter(isFilter);
  11. }
  12. const filter = toFilter(value);
  13. return filter === null ? [] : [filter];
  14. };
  15. function escapeDelimiter(value: string | undefined): string {
  16. if (value === null || value === undefined) {
  17. return '';
  18. }
  19. return /\|/g[Symbol.replace](value, '__gfp__');
  20. }
  21. function unescapeDelimiter(value: string | undefined): string {
  22. if (value === null || value === undefined) {
  23. return '';
  24. }
  25. return /__gfp__/g[Symbol.replace](value, '|');
  26. }
  27. function toArray(filter: AdHocVariableFilter): string[] {
  28. return [filter.key, filter.operator, filter.value];
  29. }
  30. function toFilter(value: string | number | boolean | undefined | null): AdHocVariableFilter | null {
  31. if (!isString(value) || value.length === 0) {
  32. return null;
  33. }
  34. const parts = value.split('|').map(unescapeDelimiter);
  35. return {
  36. key: parts[0],
  37. operator: parts[1],
  38. value: parts[2],
  39. condition: '',
  40. };
  41. }
  42. function isFilter(filter: AdHocVariableFilter | null): filter is AdHocVariableFilter {
  43. return filter !== null && isString(filter.value);
  44. }