index_pattern.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { toUtc, dateTime, DateTime, DurationUnit } from '@grafana/data';
  2. import { Interval } from './types';
  3. type IntervalMap = Record<
  4. Interval,
  5. {
  6. startOf: DurationUnit;
  7. amount: DurationUnit;
  8. }
  9. >;
  10. const intervalMap: IntervalMap = {
  11. Hourly: { startOf: 'hour', amount: 'hours' },
  12. Daily: { startOf: 'day', amount: 'days' },
  13. Weekly: { startOf: 'isoWeek', amount: 'weeks' },
  14. Monthly: { startOf: 'month', amount: 'months' },
  15. Yearly: { startOf: 'year', amount: 'years' },
  16. };
  17. export class IndexPattern {
  18. private dateLocale = 'en';
  19. constructor(private pattern: string, private interval?: keyof typeof intervalMap) {}
  20. getIndexForToday() {
  21. if (this.interval) {
  22. return toUtc().locale(this.dateLocale).format(this.pattern);
  23. } else {
  24. return this.pattern;
  25. }
  26. }
  27. getIndexList(from?: DateTime, to?: DateTime) {
  28. // When no `from` or `to` is provided, we request data from 7 subsequent/previous indices
  29. // for the provided index pattern.
  30. // This is useful when requesting log context where the only time data we have is the log
  31. // timestamp.
  32. const indexOffset = 7;
  33. if (!this.interval) {
  34. return this.pattern;
  35. }
  36. const intervalInfo = intervalMap[this.interval];
  37. const start = dateTime(from || dateTime(to).add(-indexOffset, intervalInfo.amount))
  38. .utc()
  39. .startOf(intervalInfo.startOf);
  40. const endEpoch = dateTime(to || dateTime(from).add(indexOffset, intervalInfo.amount))
  41. .utc()
  42. .startOf(intervalInfo.startOf)
  43. .valueOf();
  44. const indexList = [];
  45. while (start.valueOf() <= endEpoch) {
  46. indexList.push(start.locale(this.dateLocale).format(this.pattern));
  47. start.add(1, intervalInfo.amount);
  48. }
  49. return indexList;
  50. }
  51. }