timeserie.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { logger } from '@server/helpers/logger.js'
  2. function buildGroupByAndBoundaries (startDateString: string, endDateString: string) {
  3. const startDate = new Date(startDateString)
  4. const endDate = new Date(endDateString)
  5. const groupInterval = buildGroupInterval(startDate, endDate)
  6. logger.debug('Found "%s" group interval.', groupInterval, { startDate, endDate })
  7. // Remove parts of the date we don't need
  8. if (groupInterval.endsWith(' month') || groupInterval.endsWith(' months')) {
  9. startDate.setDate(1)
  10. startDate.setHours(0, 0, 0, 0)
  11. } else if (groupInterval.endsWith(' day') || groupInterval.endsWith(' days')) {
  12. startDate.setHours(0, 0, 0, 0)
  13. } else if (groupInterval.endsWith(' hour') || groupInterval.endsWith(' hours')) {
  14. startDate.setMinutes(0, 0, 0)
  15. } else {
  16. startDate.setSeconds(0, 0)
  17. }
  18. return {
  19. groupInterval,
  20. startDate,
  21. endDate
  22. }
  23. }
  24. // ---------------------------------------------------------------------------
  25. export {
  26. buildGroupByAndBoundaries
  27. }
  28. // ---------------------------------------------------------------------------
  29. function buildGroupInterval (startDate: Date, endDate: Date): string {
  30. const aYear = 31536000
  31. const aMonth = 2678400
  32. const aDay = 86400
  33. const anHour = 3600
  34. const aMinute = 60
  35. const diffSeconds = (endDate.getTime() - startDate.getTime()) / 1000
  36. if (diffSeconds >= 6 * aYear) return '6 months'
  37. if (diffSeconds >= 2 * aYear) return '1 month'
  38. if (diffSeconds >= 6 * aMonth) return '7 days'
  39. if (diffSeconds >= 2 * aMonth) return '2 days'
  40. if (diffSeconds >= 15 * aDay) return '1 day'
  41. if (diffSeconds >= 8 * aDay) return '12 hours'
  42. if (diffSeconds >= 4 * aDay) return '6 hours'
  43. if (diffSeconds >= 15 * anHour) return '1 hour'
  44. if (diffSeconds >= 180 * aMinute) return '10 minutes'
  45. return '1 minute'
  46. }