time.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { toUtc, RawTimeRange, TimeRange, dateMath } from '@grafana/data';
  2. import { defaultTimeRange } from '../reports/state/reducers';
  3. import { ReportTimeRange } from '../types';
  4. const isValidTimeRange = (range: any) => {
  5. return dateMath.isValid(range.from) && dateMath.isValid(range.to);
  6. };
  7. /**
  8. * Get a string representation of range timestamp to be sent to backend
  9. * @param timeRange
  10. */
  11. export const parseRange = (timeRange?: RawTimeRange): ReportTimeRange => {
  12. if (!timeRange || !isValidTimeRange(timeRange)) {
  13. return { from: '', to: '' };
  14. }
  15. return {
  16. to: timeRange.to.valueOf().toString(),
  17. from: timeRange.from.valueOf().toString(),
  18. };
  19. };
  20. /**
  21. * Return relative time e.g. 'now', 'now-6h' or a parsed timestamp
  22. * @param timeRange
  23. */
  24. export const getRange = (timeRange: any): TimeRange => {
  25. const from = parseValue(timeRange.from);
  26. const to = parseValue(timeRange.to);
  27. if (!isValidTimeRange({ from, to })) {
  28. return defaultTimeRange;
  29. }
  30. return { from, to, raw: { from, to } };
  31. };
  32. const parseValue = (value: any) => {
  33. const parsed = parseInt(value, 10);
  34. if (!isNaN(parsed)) {
  35. return toUtc(parsed);
  36. }
  37. return value;
  38. };