2020-06-04 06:44:48 -05:00
|
|
|
import { AdHocVariableFilter } from 'app/features/variables/types';
|
2020-04-20 00:37:38 -05:00
|
|
|
import { UrlQueryValue } from '@grafana/data';
|
2020-03-23 23:46:31 -05:00
|
|
|
import { isArray, isString } from 'lodash';
|
2020-03-23 03:00:36 -05:00
|
|
|
|
|
|
|
export const toUrl = (filters: AdHocVariableFilter[]): string[] => {
|
2021-01-20 00:59:48 -06:00
|
|
|
return filters.map((filter) => toArray(filter).map(escapeDelimiter).join('|'));
|
2020-03-23 03:00:36 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
export const toFilters = (value: UrlQueryValue): AdHocVariableFilter[] => {
|
|
|
|
if (isArray(value)) {
|
|
|
|
const values = value as any[];
|
|
|
|
return values.map(toFilter).filter(isFilter);
|
|
|
|
}
|
|
|
|
|
|
|
|
const filter = toFilter(value);
|
|
|
|
return filter === null ? [] : [filter];
|
|
|
|
};
|
|
|
|
|
2020-10-14 05:55:28 -05:00
|
|
|
function escapeDelimiter(value: string | undefined): string {
|
2021-02-22 03:35:36 -06:00
|
|
|
if (value === null || value === undefined) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return /\|/g[Symbol.replace](value, '__gfp__');
|
2020-03-23 03:00:36 -05:00
|
|
|
}
|
|
|
|
|
2020-10-14 05:55:28 -05:00
|
|
|
function unescapeDelimiter(value: string | undefined): string {
|
2021-02-22 03:35:36 -06:00
|
|
|
if (value === null || value === undefined) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return /__gfp__/g[Symbol.replace](value, '|');
|
2020-03-23 03:00:36 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function toArray(filter: AdHocVariableFilter): string[] {
|
|
|
|
return [filter.key, filter.operator, filter.value];
|
|
|
|
}
|
|
|
|
|
|
|
|
function toFilter(value: string | number | boolean | undefined | null): AdHocVariableFilter | null {
|
|
|
|
if (!isString(value) || value.length === 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const parts = value.split('|').map(unescapeDelimiter);
|
|
|
|
|
|
|
|
return {
|
|
|
|
key: parts[0],
|
|
|
|
operator: parts[1],
|
|
|
|
value: parts[2],
|
|
|
|
condition: '',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function isFilter(filter: AdHocVariableFilter | null): filter is AdHocVariableFilter {
|
|
|
|
return filter !== null && isString(filter.value);
|
|
|
|
}
|