getPeriod.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import moment from 'moment';
  2. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  3. import {DateString} from 'sentry/types';
  4. import {getUtcDateString} from 'sentry/utils/dates';
  5. type DateObject = {
  6. /**
  7. * Ending date object
  8. */
  9. end?: DateString;
  10. /**
  11. * Relative period string in format "<int><unit>" (e.g. 4d for 4 days)
  12. */
  13. period?: string | null;
  14. /**
  15. * Starting date object
  16. */
  17. start?: DateString;
  18. };
  19. type Options = {
  20. /**
  21. * Doubles the given period (useful for getting previous period data)
  22. */
  23. shouldDoublePeriod?: boolean;
  24. };
  25. /**
  26. * Gets the period to query with if we need to double the initial period in order
  27. * to get data for the previous period
  28. *
  29. * Returns an object with either a period or start/end dates ({statsPeriod: string} or {start: string, end: string})
  30. */
  31. export function getPeriod(
  32. {period, start, end}: DateObject,
  33. {shouldDoublePeriod}: Options = {}
  34. ) {
  35. if (!period && !start && !end) {
  36. period = DEFAULT_STATS_PERIOD;
  37. }
  38. // you can not specify both relative and absolute periods
  39. // relative period takes precedence
  40. if (period) {
  41. if (!shouldDoublePeriod) {
  42. return {statsPeriod: period};
  43. }
  44. const [, periodNumber, periodLength] = period.match(/([0-9]+)([mhdw])/)!;
  45. return {statsPeriod: `${parseInt(periodNumber, 10) * 2}${periodLength}`};
  46. }
  47. if (!start || !end) {
  48. throw new Error('start and end required');
  49. }
  50. const formattedStart = getUtcDateString(start);
  51. const formattedEnd = getUtcDateString(end);
  52. if (shouldDoublePeriod) {
  53. // get duration of end - start and double
  54. const diff = moment(end).diff(moment(start));
  55. const previousPeriodStart = moment(start).subtract(diff);
  56. // This is not as accurate as having 2 start/end objs
  57. return {
  58. start: getUtcDateString(previousPeriodStart),
  59. end: formattedEnd,
  60. };
  61. }
  62. return {
  63. start: formattedStart,
  64. end: formattedEnd,
  65. };
  66. }