@grafana/data#TimeRange TypeScript Examples

The following examples show how to use @grafana/data#TimeRange. 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: TimePickerWithHistory.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
function convertIfJson(history: TimeRange[]): TimeRange[] {
  return history.map(time => {
    if (isDateTime(time.from)) {
      return time;
    }

    return {
      from: dateTime(time.from),
      to: dateTime(time.to),
      raw: time.raw,
    };
  });
}
Example #2
Source File: timePicker.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getShiftedTimeRange = (direction: number, origRange: TimeRange): AbsoluteTimeRange => {
  const range = {
    from: toUtc(origRange.from),
    to: toUtc(origRange.to),
  };

  const timespan = (range.to.valueOf() - range.from.valueOf()) / 2;
  let to: number, from: number;

  if (direction === -1) {
    to = range.to.valueOf() - timespan;
    from = range.from.valueOf() - timespan;
  } else if (direction === 1) {
    to = range.to.valueOf() + timespan;
    from = range.from.valueOf() + timespan;
    if (to > Date.now() && range.to.valueOf() < Date.now()) {
      to = Date.now();
      from = range.from.valueOf();
    }
  } else {
    to = range.to.valueOf();
    from = range.from.valueOf();
  }

  return { from, to };
}
Example #3
Source File: kbn.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
kbn.calculateInterval = (range: TimeRange, resolution: number, lowLimitInterval: string[]) => {
  let lowLimitMs = 1; // 1 millisecond default low limit
  let intervalMs;

  if (lowLimitInterval) {
    if (lowLimitInterval[0] === '>') {
      lowLimitInterval = lowLimitInterval.slice(1);
    }
    lowLimitMs = kbn.interval_to_ms(lowLimitInterval);
  }

  intervalMs = kbn.round_interval((range.to.valueOf() - range.from.valueOf()) / resolution);
  if (lowLimitMs > intervalMs) {
    intervalMs = lowLimitMs;
  }

  return {
    intervalMs: intervalMs,
    interval: kbn.secondsToHms(intervalMs / 1000),
  };
};
Example #4
Source File: explore.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  const raw = {
    from: parseRawTime(range.from),
    to: parseRawTime(range.to),
  };

  return {
    from: dateMath.parse(raw.from, false, timeZone as any),
    to: dateMath.parse(raw.to, true, timeZone as any),
    raw,
  };
}
Example #5
Source File: actions.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
toRawTimeRange = (range: TimeRange): RawTimeRange => {
  let from = range.raw.from;
  if (isDateTime(from)) {
    from = from.valueOf().toString(10);
  }

  let to = range.raw.to;
  if (isDateTime(to)) {
    to = to.valueOf().toString(10);
  }

  return {
    from,
    to,
  };
}
Example #6
Source File: timePicker.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getZoomedTimeRange = (range: TimeRange, factor: number): AbsoluteTimeRange => {
  const timespan = range.to.valueOf() - range.from.valueOf();
  const center = range.to.valueOf() - timespan / 2;

  const to = center + (timespan * factor) / 2;
  const from = center - (timespan * factor) / 2;

  return { from, to };
}
Example #7
Source File: annotations_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getAnnotations(options: { dashboard: DashboardModel; panel: PanelModel; range: TimeRange }) {
    return Promise.all([this.getGlobalAnnotations(options), this.getAlertStates(options)])
      .then(results => {
        // combine the annotations and flatten results
        let annotations: AnnotationEvent[] = flattenDeep(results[0]);

        // filter out annotations that do not belong to requesting panel
        annotations = annotations.filter(item => {
          // if event has panel id and query is of type dashboard then panel and requesting panel id must match
          if (item.panelId && item.source.type === 'dashboard') {
            return item.panelId === options.panel.id;
          }
          return true;
        });

        annotations = dedupAnnotations(annotations);

        // look for alert state for this panel
        const alertState: any = results[1].find((res: any) => res.panelId === options.panel.id);

        return {
          annotations: annotations,
          alertState: alertState,
        };
      })
      .catch(err => {
        if (!err.message && err.data && err.data.message) {
          err.message = err.data.message;
        }
        console.log('AnnotationSrv.query error', err);
        appEvents.emit(AppEvents.alertError, ['Annotation Query Failed', err.message || err]);
        return [];
      });
  }
Example #8
Source File: TimePickerWithHistory.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
TimePickerWithHistory: React.FC<Props> = props => {
  return (
    <LocalStorageValueProvider<TimeRange[]> storageKey={LOCAL_STORAGE_KEY} defaultValue={[]}>
      {(values, onSaveToStore) => {
        return (
          <TimePicker
            {...props}
            history={convertIfJson(values)}
            onChange={value => {
              onAppendToHistory(value, values, onSaveToStore);
              props.onChange(value);
            }}
          />
        );
      }}
    </LocalStorageValueProvider>
  );
}
Example #9
Source File: actions.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize Explore state with state from the URL and the React component.
 * Call this only on components for with the Explore state has not been initialized.
 */
export function initializeExplore(
  exploreId: ExploreId,
  datasourceName: string,
  queries: DataQuery[],
  range: TimeRange,
  mode: ExploreMode,
  containerWidth: number,
  eventBridge: Emitter,
  ui: ExploreUIState,
  originPanelId: number
): ThunkResult<void> {
  return async (dispatch, getState) => {
    dispatch(loadExploreDatasourcesAndSetDatasource(exploreId, datasourceName));
    dispatch(
      initializeExploreAction({
        exploreId,
        containerWidth,
        eventBridge,
        queries,
        range,
        mode,
        ui,
        originPanelId,
      })
    );
    dispatch(updateTime({ exploreId }));
    const richHistory = getRichHistory();
    dispatch(richHistoryUpdatedAction({ richHistory }));
  };
}
Example #10
Source File: DashNavTimeControls.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
onChangeTimePicker = (timeRange: TimeRange) => {
    const { dashboard } = this.props;
    const panel = dashboard.timepicker;
    const hasDelay = panel.nowDelay && timeRange.raw.to === 'now';

    const adjustedFrom = dateMath.isMathString(timeRange.raw.from) ? timeRange.raw.from : timeRange.from;
    const adjustedTo = dateMath.isMathString(timeRange.raw.to) ? timeRange.raw.to : timeRange.to;
    const nextRange = {
      from: adjustedFrom,
      to: hasDelay ? 'now-' + panel.nowDelay : adjustedTo,
    };

    getTimeSrv().setTime(nextRange);
  };
Example #11
Source File: variable_srv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
onTimeRangeUpdated(timeRange: TimeRange) {
    this.templateSrv.updateTimeRange(timeRange);
    const promises = this.variables
      .filter(variable => variable.refresh === 2)
      .map(variable => {
        const previousOptions = variable.options.slice();

        return variable.updateOptions().then(() => {
          if (angular.toJson(previousOptions) !== angular.toJson(variable.options)) {
            this.dashboard.templateVariableValueUpdated();
          }
        });
      });

    return this.$q
      .all(promises)
      .then(() => {
        this.dashboard.startRefresh();
      })
      .catch(e => {
        appEvents.emit(AppEvents.alertError, ['Template variable service failed', e.message]);
      });
  }
Example #12
Source File: TimeSrv.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
timeRange(): TimeRange {
    // make copies if they are moment  (do not want to return out internal moment, because they are mutable!)
    const raw = {
      from: isDateTime(this.time.from) ? dateTime(this.time.from) : this.time.from,
      to: isDateTime(this.time.to) ? dateTime(this.time.to) : this.time.to,
    };

    const timezone: TimeZone = this.dashboard ? this.dashboard.getTimezone() : undefined;

    return {
      from: dateMath.parse(raw.from, false, timezone),
      to: dateMath.parse(raw.to, true, timezone),
      raw: raw,
    };
  }
Example #13
Source File: mapper.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
mapStringsToTimeRange = (from: string, to: string, roundup?: boolean, timeZone?: TimeZone): TimeRange => {
  const fromDate = stringToDateTimeType(from, roundup, timeZone);
  const toDate = stringToDateTimeType(to, roundup, timeZone);

  if (dateMath.isMathString(from) || dateMath.isMathString(to)) {
    return {
      from: fromDate,
      to: toDate,
      raw: {
        from,
        to,
      },
    };
  }

  return {
    from: fromDate,
    to: toDate,
    raw: {
      from: fromDate,
      to: toDate,
    },
  };
}
Example #14
Source File: mapper.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
mapRangeToTimeOption = (range: TimeRange, timeZone?: TimeZone): TimeOption => {
  const formattedFrom = stringToDateTime(range.from, false, timeZone).format(TIME_FORMAT);
  const formattedTo = stringToDateTime(range.to, true, timeZone).format(TIME_FORMAT);
  const from = dateTimeToString(range.from, timeZone);
  const to = dateTimeToString(range.to, timeZone);

  return {
    from,
    to,
    section: 3,
    display: `${formattedFrom} to ${formattedTo}`,
  };
}
Example #15
Source File: mapper.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
mapOptionToTimeRange = (option: TimeOption, timeZone?: TimeZone): TimeRange => {
  return {
    from: stringToDateTime(option.from, false, timeZone),
    to: stringToDateTime(option.to, true, timeZone),
    raw: {
      from: option.from,
      to: option.to,
    },
  };
}
Example #16
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
runLegacyQuery = (
    target: LokiQuery,
    options: { range?: TimeRange; maxDataPoints?: number; reverse?: boolean }
  ): Observable<DataQueryResponse> => {
    if (target.liveStreaming) {
      return this.runLiveQuery(target, options);
    }

    const range = options.range
      ? { start: this.getTime(options.range.from, false), end: this.getTime(options.range.to, true) }
      : {};
    const query: LokiLegacyQueryRequest = {
      ...DEFAULT_QUERY_PARAMS,
      ...parseQuery(target.expr),
      ...range,
      limit: Math.min(options.maxDataPoints || Infinity, this.maxLines),
      refId: target.refId,
    };

    return this._request(LEGACY_QUERY_ENDPOINT, query).pipe(
      catchError((err: any) => this.throwUnless(err, err.cancelled, target)),
      filter((response: any) => !response.cancelled),
      map((response: { data: LokiLegacyStreamResponse }) => ({
        data: lokiLegacyStreamsToDataframes(
          response.data,
          query,
          this.maxLines,
          this.instanceSettings.jsonData,
          options.reverse
        ),
        key: `${target.refId}_log`,
      }))
    );
  };
Example #17
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
getRangeScopedVars(range: TimeRange = getTimeSrv().timeRange()) {
    const msRange = range.to.diff(range.from);
    const sRange = Math.round(msRange / 1000);
    return {
      __range_ms: { text: msRange, value: msRange },
      __range_s: { text: sRange, value: sRange },
      __range: { text: sRange + 's', value: sRange + 's' },
    };
  }
Example #18
Source File: QueryStatus.test.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
describe('<QueryStatus />', () => {
  it('should render with a latency', () => {
    const res: PanelData = { series: [], state: LoadingState.Done, timeRange: {} as TimeRange };
    const wrapper = shallow(<QueryStatus latency={0} queryResponse={res} />);
    expect(wrapper.find('div').exists()).toBeTruthy();
  });
  it('should not render when query has not started', () => {
    const res: PanelData = { series: [], state: LoadingState.NotStarted, timeRange: {} as TimeRange };
    const wrapper = shallow(<QueryStatus latency={0} queryResponse={res} />);
    expect(wrapper.getElement()).toBe(null);
  });
});
Example #19
Source File: QueryEditor.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
initTimeSrv(range: TimeRange) {
    const timeSrv = getTimeSrv();
    timeSrv.init({
      time: {
        from: dateTime(range.from),
        to: dateTime(range.to),
      },
      refresh: false,
      getTimezone: () => 'utc',
      timeRangeUpdated: () => console.log('refreshDashboard!'),
    });
  }
Example #20
Source File: data_processor.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
private toTimeSeries(
    field: Field,
    alias: string,
    dataFrameIndex: number,
    fieldIndex: number,
    datapoints: any[][],
    index: number,
    range?: TimeRange
  ) {
    const colorIndex = index % colors.length;
    const color = this.panel.aliasColors[alias] || colors[colorIndex];

    const series = new TimeSeries({
      datapoints: datapoints || [],
      alias: alias,
      color: getColorFromHexRgbOrName(color, config.theme.type),
      unit: field.config ? field.config.unit : undefined,
      dataFrameIndex,
      fieldIndex,
    });

    if (datapoints && datapoints.length > 0 && range) {
      const last = datapoints[datapoints.length - 1][1];
      const from = range.from;

      if (last - from.valueOf() < -10000) {
        series.isOutsideRange = true;
      }
    }
    return series;
  }
Example #21
Source File: ExploreTimeControls.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
onChangeTimePicker = (timeRange: TimeRange) => {
    this.props.onChangeTime(timeRange.raw);
  };
Example #22
Source File: TimePicker.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
onChange = (timeRange: TimeRange) => {
    this.props.onChange(timeRange);
    this.setState({ isOpen: false });
  };
Example #23
Source File: metrics_panel_ctrl.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
range: TimeRange;
Example #24
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
init(variables: any, timeRange?: TimeRange) {
    this.variables = variables;
    this.timeRange = timeRange;
    this.updateIndex();
  }
Example #25
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
updateTimeRange(timeRange: TimeRange) {
    this.timeRange = timeRange;
    this.updateIndex();
  }
Example #26
Source File: template_srv.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
private timeRange?: TimeRange | null = null;
Example #27
Source File: datasource.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
performTimeSeriesQuery(request: any, { from, to }: TimeRange): Promise<any> {
    return this.awsRequest('/api/tsdb/query', request)
      .then((res: any) => {
        if (!res.results) {
          return { data: [] };
        }
        return Object.values(request.queries).reduce(
          ({ data, error }: any, queryRequest: any) => {
            const queryResult = res.results[queryRequest.refId];
            if (!queryResult) {
              return { data, error };
            }

            const link = this.buildCloudwatchConsoleUrl(
              queryRequest,
              from.toISOString(),
              to.toISOString(),
              queryRequest.refId,
              queryResult.meta.gmdMeta
            );

            return {
              error: error || queryResult.error ? { message: queryResult.error } : null,
              data: [
                ...data,
                ...queryResult.series.map(({ name, points }: any) => {
                  const dataFrame = toDataFrame({
                    target: name,
                    datapoints: points,
                    refId: queryRequest.refId,
                    meta: queryResult.meta,
                  });
                  if (link) {
                    for (const field of dataFrame.fields) {
                      field.config.links = [
                        {
                          url: link,
                          title: 'View in CloudWatch console',
                          targetBlank: true,
                        },
                      ];
                    }
                  }
                  return dataFrame;
                }),
              ],
            };
          },
          { data: [], error: null }
        );
      })
      .catch((err: any = { data: { error: '' } }) => {
        if (/^Throttling:.*/.test(err.data.message)) {
          const failedRedIds = Object.keys(err.data.results);
          const regionsAffected = Object.values(request.queries).reduce(
            (res: string[], { refId, region }: CloudWatchQuery) =>
              !failedRedIds.includes(refId) || res.includes(region) ? res : [...res, region],
            []
          ) as string[];

          regionsAffected.forEach(region => this.debouncedAlert(this.datasourceName, this.getActualRegion(region)));
        }

        if (err.data && err.data.message === 'Metric request error' && err.data.error) {
          err.data.message = err.data.error;
        }

        throw err;
      });
  }
Example #28
Source File: metric_find_query.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
range: TimeRange;
Example #29
Source File: BarGaugePanel.test.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
function createTimeRange(): TimeRange {
  return {
    from: dateMath.parse('now-6h') || dateTime(),
    to: dateMath.parse('now') || dateTime(),
    raw: { from: 'now-6h', to: 'now' },
  };
}