@grafana/data#ScopedVars TypeScript Examples

The following examples show how to use @grafana/data#ScopedVars. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(queries: GraphiteQuery[], scopedVars: ScopedVars): GraphiteQuery[] {
    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          target: this.templateSrv.replace(query.target, scopedVars),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #2
Source File: renderer.test.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
templateSrv = {
  replace: (value: any, scopedVars: ScopedVars) => {
    if (scopedVars) {
      // For testing variables replacement in link
      _.each(scopedVars, (val, key) => {
        value = value.replace('$' + key, val.value);
      });
    }
    return value;
  },
}
Example #3
Source File: renderer.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
renderRowVariables(rowIndex: number) {
    const scopedVars: ScopedVars = {};
    let cellVariable;
    const row = this.table.rows[rowIndex];
    for (let i = 0; i < row.length; i++) {
      cellVariable = `__cell_${i}`;
      scopedVars[cellVariable] = { value: row[i], text: row[i] ? row[i].toString() : '' };
    }
    return scopedVars;
  }
Example #4
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateFilters(filters: string[], scopedVars: ScopedVars) {
    const completeFilter = _.chunk(filters, 4)
      .map(([key, operator, value, condition = 'AND']) => ({
        key,
        operator,
        value,
        condition,
      }))
      .reduce((res, filter) => (filter.value ? [...res, filter] : res), []);

    const filterArray = _.flatten(
      completeFilter.map(({ key, operator, value, condition }: Filter) => [
        this.templateSrv.replace(key, scopedVars || {}),
        operator,
        this.templateSrv.replace(value, scopedVars || {}, 'regex'),
        condition,
      ])
    );

    return filterArray || [];
  }
Example #5
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(queries: PromQuery[], scopedVars: ScopedVars): PromQuery[] {
    let expandedQueries = queries;
    if (queries && queries.length) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          expr: templateSrv.replace(query.expr, scopedVars, this.interpolateQueryExpr),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #6
Source File: postgres_query.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/** @ngInject */
  constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    this.scopedVars = scopedVars;

    target.format = target.format || 'time_series';
    target.timeColumn = target.timeColumn || 'time';
    target.metricColumn = target.metricColumn || 'none';

    target.group = target.group || [];
    target.where = target.where || [{ type: 'macro', name: '$__timeFilter', params: [] }];
    target.select = target.select || [[{ type: 'column', params: ['value'] }]];

    // handle pre query gui panels gracefully
    if (!('rawQuery' in this.target)) {
      if ('rawSql' in target) {
        // pre query gui panel
        target.rawQuery = true;
      } else {
        // new panel
        target.rawQuery = false;
      }
    }

    // give interpolateQueryStr access to this
    this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
  }
Example #7
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(
    queries: PostgresQueryForInterpolation[],
    scopedVars: ScopedVars
  ): PostgresQueryForInterpolation[] {
    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #8
Source File: mysql_query.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/** @ngInject */
  constructor(target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    this.scopedVars = scopedVars;

    target.format = target.format || 'time_series';
    target.timeColumn = target.timeColumn || 'time';
    target.metricColumn = target.metricColumn || 'none';

    target.group = target.group || [];
    target.where = target.where || [{ type: 'macro', name: '$__timeFilter', params: [] }];
    target.select = target.select || [[{ type: 'column', params: ['value'] }]];

    // handle pre query gui panels gracefully
    if (!('rawQuery' in this.target)) {
      if ('rawSql' in target) {
        // pre query gui panel
        target.rawQuery = true;
      } else {
        // new panel
        target.rawQuery = false;
      }
    }

    // give interpolateQueryStr access to this
    this.interpolateQueryStr = this.interpolateQueryStr.bind(this);
  }
Example #9
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(
    queries: MysqlQueryForInterpolation[],
    scopedVars: ScopedVars
  ): MysqlQueryForInterpolation[] {
    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #10
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(
    queries: MssqlQueryForInterpolation[],
    scopedVars: ScopedVars
  ): MssqlQueryForInterpolation[] {
    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          rawSql: this.templateSrv.replace(query.rawSql, scopedVars, this.interpolateVariable),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #11
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(queries: LokiQuery[], scopedVars: ScopedVars): LokiQuery[] {
    let expandedQueries = queries;
    if (queries && queries.length) {
      expandedQueries = queries.map(query => ({
        ...query,
        datasource: this.name,
        expr: this.templateSrv.replace(query.expr, scopedVars, this.interpolateQueryExpr),
      }));
    }

    return expandedQueries;
  }
Example #12
Source File: influx_query_model.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/** @ngInject */
  constructor(target: InfluxQuery, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
    this.target = target;
    this.templateSrv = templateSrv;
    this.scopedVars = scopedVars;

    target.policy = target.policy || 'default';
    target.resultFormat = target.resultFormat || 'time_series';
    target.orderByTime = target.orderByTime || 'ASC';
    target.tags = target.tags || [];
    target.groupBy = target.groupBy || [
      { type: 'time', params: ['$__interval'] },
      { type: 'fill', params: ['null'] },
    ];
    target.select = target.select || [
      [
        { type: 'field', params: ['value'] },
        { type: 'mean', params: [] },
      ],
    ];

    this.updateProjection();
  }
Example #13
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(queries: InfluxQuery[], scopedVars: ScopedVars): InfluxQuery[] {
    if (!queries || queries.length === 0) {
      return [];
    }

    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          measurement: this.templateSrv.replace(query.measurement, scopedVars, 'regex'),
        };

        if (query.rawQuery) {
          expandedQuery.query = this.templateSrv.replace(query.query, scopedVars, 'regex');
        }

        if (query.tags) {
          const expandedTags = query.tags.map(tag => {
            const expandedTag = {
              ...tag,
              value: this.templateSrv.replace(tag.value, null, 'regex'),
            };
            return expandedTag;
          });
          expandedQuery.tags = expandedTags;
        }
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #14
Source File: graphite_query.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/** @ngInject */
  constructor(datasource: any, target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
    this.datasource = datasource;
    this.target = target;
    this.templateSrv = templateSrv;
    this.scopedVars = scopedVars;
    this.parseTarget();

    this.removeTagValue = '-- remove tag --';
  }
Example #15
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
interpolateVariablesInQueries(queries: ElasticsearchQuery[], scopedVars: ScopedVars): ElasticsearchQuery[] {
    let expandedQueries = queries;
    if (queries && queries.length > 0) {
      expandedQueries = queries.map(query => {
        const expandedQuery = {
          ...query,
          datasource: this.name,
          query: this.templateSrv.replace(query.query, scopedVars, 'lucene'),
        };
        return expandedQuery;
      });
    }
    return expandedQueries;
  }
Example #16
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
replace(target: string, scopedVars: ScopedVars, displayErrorIfIsMultiTemplateVariable?: boolean, fieldName?: string) {
    if (displayErrorIfIsMultiTemplateVariable) {
      const variable = this.templateSrv.variables.find(({ name }) => name === this.templateSrv.getVariableName(target));
      if (variable && variable.multi) {
        this.debouncedCustomAlert(
          'CloudWatch templating error',
          `Multi template variables are not supported for ${fieldName || target}`
        );
      }
    }

    return this.templateSrv.replace(target, scopedVars);
  }
Example #17
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
convertDimensionFormat(dimensions: { [key: string]: string | string[] }, scopedVars: ScopedVars) {
    return Object.entries(dimensions).reduce((result, [key, value]) => {
      key = this.replace(key, scopedVars, true, 'dimension keys');

      if (Array.isArray(value)) {
        return { ...result, [key]: value };
      }

      const valueVar = this.templateSrv.variables.find(({ name }) => name === this.templateSrv.getVariableName(value));
      if (valueVar) {
        if (valueVar.multi) {
          const values = this.templateSrv.replace(value, scopedVars, 'pipe').split('|');
          return { ...result, [key]: values };
        }
        return { ...result, [key]: [this.templateSrv.replace(value, scopedVars)] };
      }

      return { ...result, [key]: [value] };
    }, {});
  }
Example #18
Source File: variable.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getSearchFilterScopedVar = (args: {
  query: string;
  wildcardChar: string;
  options: { searchFilter?: string };
}): ScopedVars => {
  const { query, wildcardChar } = args;
  if (!containsSearchFilter(query)) {
    return {};
  }

  let { options } = args;

  options = options || { searchFilter: '' };
  const value = options.searchFilter ? `${options.searchFilter}${wildcardChar}` : `${wildcardChar}`;

  return {
    __searchFilter: {
      value,
      text: '',
    },
  };
}
Example #19
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
fillVariableValuesForUrl(params: any, scopedVars?: ScopedVars) {
    _.each(this.variables, variable => {
      if (scopedVars && scopedVars[variable.name] !== void 0) {
        if (scopedVars[variable.name].skipUrlSync) {
          return;
        }
        params['var-' + variable.name] = scopedVars[variable.name].value;
      } else {
        if (variable.skipUrlSync) {
          return;
        }
        params['var-' + variable.name] = variable.getValueForUrl();
      }
    });
  }
Example #20
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
replaceWithText(target: string, scopedVars?: ScopedVars) {
    if (!target) {
      return target;
    }

    let variable;
    this.regex.lastIndex = 0;

    return target.replace(this.regex, (match: any, var1: any, var2: any, fmt2: any, var3: any) => {
      if (scopedVars) {
        const option = scopedVars[var1 || var2 || var3];
        if (option) {
          return option.text;
        }
      }

      variable = this.getVariableAtIndex(var1 || var2 || var3);
      if (!variable) {
        return match;
      }

      const value = this.grafanaVariables[variable.current.value];

      return typeof value === 'string' ? value : variable.current.text;
    });
  }
Example #21
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getVariableValue(variableName: string, fieldPath: string | undefined, scopedVars: ScopedVars) {
    const scopedVar = scopedVars[variableName];
    if (!scopedVar) {
      return null;
    }

    if (fieldPath) {
      return this.getFieldAccessor(fieldPath)(scopedVar.value);
    }

    return scopedVar.value;
  }
Example #22
Source File: datasource_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
get(name?: string, scopedVars?: ScopedVars): Promise<DataSourceApi> {
    if (!name) {
      return this.get(config.defaultDatasource);
    }

    // Interpolation here is to support template variable in data source selection
    name = this.templateSrv.replace(name, scopedVars, (value: any[]) => {
      if (Array.isArray(value)) {
        return value[0];
      }
      return value;
    });

    if (name === 'default') {
      return this.get(config.defaultDatasource);
    }

    if (this.datasources[name]) {
      return Promise.resolve(this.datasources[name]);
    }

    return this.loadDatasource(name);
  }
Example #23
Source File: link_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/**
   * getPanelLinkAnchorInfo method is left for plugins compatibility reasons
   *
   * @deprecated Drilldown links should be generated using getDataLinkUIModel method
   */
  getPanelLinkAnchorInfo(link: DataLink, scopedVars: ScopedVars) {
    deprecationWarning('link_srv.ts', 'getPanelLinkAnchorInfo', 'getDataLinkUIModel');
    return this.getDataLinkUIModel(link, scopedVars, {});
  }
Example #24
Source File: PanelQueryRunner.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
async function getDataSource(
  datasource: string | DataSourceApi | null,
  scopedVars: ScopedVars
): Promise<DataSourceApi> {
  if (datasource && (datasource as any).query) {
    return datasource as DataSourceApi;
  }
  return await getDatasourceSrv().get(datasource as string, scopedVars);
}
Example #25
Source File: PanelChrome.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
replaceVariables = (value: string, extraVars?: ScopedVars, format?: string) => {
    let vars = this.props.panel.scopedVars;
    if (extraVars) {
      vars = vars ? { ...vars, ...extraVars } : extraVars;
    }
    return templateSrv.replace(value, vars, format);
  };
Example #26
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
buildGraphiteParams(options: any, scopedVars: ScopedVars): string[] {
    const graphiteOptions = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
    const cleanOptions = [],
      targets: any = {};
    let target, targetValue, i;
    const regex = /\#([A-Z])/g;
    const intervalFormatFixRegex = /'(\d+)m'/gi;
    let hasTargets = false;

    options['format'] = 'json';

    function fixIntervalFormat(match: any) {
      return match.replace('m', 'min').replace('M', 'mon');
    }

    for (i = 0; i < options.targets.length; i++) {
      target = options.targets[i];
      if (!target.target) {
        continue;
      }

      if (!target.refId) {
        target.refId = this._seriesRefLetters[i];
      }

      targetValue = this.templateSrv.replace(target.target, scopedVars);
      targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
      targets[target.refId] = targetValue;
    }

    function nestedSeriesRegexReplacer(match: any, g1: string | number) {
      return targets[g1] || match;
    }

    for (i = 0; i < options.targets.length; i++) {
      target = options.targets[i];
      if (!target.target) {
        continue;
      }

      targetValue = targets[target.refId];
      targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
      targets[target.refId] = targetValue;

      if (!target.hide) {
        hasTargets = true;
        cleanOptions.push('target=' + encodeURIComponent(targetValue));
      }
    }

    _.each(options, (value, key) => {
      if (_.indexOf(graphiteOptions, key) === -1) {
        return;
      }
      if (value) {
        cleanOptions.push(key + '=' + encodeURIComponent(value));
      }
    });

    if (!hasTargets) {
      return [];
    }

    return cleanOptions;
  }
Example #27
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
replace(target: string, scopedVars?: ScopedVars, format?: string | Function): any {
    if (!target) {
      return target;
    }

    this.regex.lastIndex = 0;

    return target.replace(this.regex, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
      const variableName = var1 || var2 || var3;
      const variable = this.getVariableAtIndex(variableName);
      const fmt = fmt2 || fmt3 || format;

      if (scopedVars) {
        const value = this.getVariableValue(variableName, fieldPath, scopedVars);
        if (value !== null && value !== undefined) {
          return this.formatValue(value, fmt, variable);
        }
      }

      if (!variable) {
        return match;
      }

      const systemValue = this.grafanaVariables[variable.current.value];
      if (systemValue) {
        return this.formatValue(systemValue, fmt, variable);
      }

      let value = variable.current.value;
      if (this.isAllValue(value)) {
        value = this.getAllValue(variable);
        // skip formatting of custom all values
        if (variable.allValue) {
          return this.replace(value);
        }
      }

      if (fieldPath) {
        const fieldValue = this.getVariableValue(variableName, fieldPath, {
          [variableName]: { value: value, text: '' },
        });
        if (fieldValue !== null && fieldValue !== undefined) {
          return this.formatValue(fieldValue, fmt, variable);
        }
      }

      const res = this.formatValue(value, fmt, variable);
      return res;
    });
  }
Example #28
Source File: link_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
/**
   * Returns LinkModel which is basically a DataLink with all values interpolated through the templateSrv.
   */
  getDataLinkUIModel = <T>(link: DataLink, scopedVars: ScopedVars, origin: T): LinkModel<T> => {
    const params: KeyValue = {};
    const timeRangeUrl = toUrlParams(this.timeSrv.timeRangeForUrl());

    let href = link.url;

    if (link.onBuildUrl) {
      href = link.onBuildUrl({
        origin,
        scopedVars,
      });
    }

    let onClick: (e: any) => void = undefined;

    if (link.onClick) {
      onClick = (e: any) => {
        link.onClick({
          origin,
          scopedVars,
          e,
        });
      };
    }

    const info: LinkModel<T> = {
      href: locationUtil.assureBaseUrl(href.replace(/\n/g, '')),
      title: this.templateSrv.replace(link.title || '', scopedVars),
      target: link.targetBlank ? '_blank' : '_self',
      origin,
      onClick,
    };

    this.templateSrv.fillVariableValuesForUrl(params, scopedVars);

    const variablesQuery = toUrlParams(params);

    info.href = this.templateSrv.replace(info.href, {
      ...scopedVars,
      [DataLinkBuiltInVars.keepTime]: {
        text: timeRangeUrl,
        value: timeRangeUrl,
      },
      [DataLinkBuiltInVars.includeVars]: {
        text: variablesQuery,
        value: variablesQuery,
      },
    });

    info.href = getConfig().disableSanitizeHtml ? info.href : sanitizeUrl(info.href);

    return info;
  };
Example #29
Source File: PanelModel.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
scopedVars?: ScopedVars;