From 290a4c18bfb8a8113741442743e00c471d224295 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivar=20Conradi=20=C3=98sthus?= Date: Fri, 8 Oct 2021 09:53:33 +0200 Subject: [PATCH] fix: use modulo instead for Math.floor for rounding down to full hour --- src/lib/db/client-metrics-store-v2.ts | 5 +---- .../e2e/stores/client-metrics-store-v2.e2e.test.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/lib/db/client-metrics-store-v2.ts b/src/lib/db/client-metrics-store-v2.ts index 8e77e88db8..e3ac091369 100644 --- a/src/lib/db/client-metrics-store-v2.ts +++ b/src/lib/db/client-metrics-store-v2.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import util from 'util'; import { Knex } from 'knex'; import { Logger, LogProvider } from '../logger'; import { @@ -20,10 +19,8 @@ interface ClientMetricsEnvTable { const TABLE = 'client_metrics_env'; -// Unsure if this would be better be done by the service? export function roundDownToHour(date: Date): Date { - let p = 60 * 60 * 1000; // milliseconds in an hour - return new Date(Math.floor(date.getTime() / p) * p); + return new Date(date.getTime() - (date.getTime() % 3600000)); } const fromRow = (row: ClientMetricsEnvTable) => ({ diff --git a/src/test/e2e/stores/client-metrics-store-v2.e2e.test.ts b/src/test/e2e/stores/client-metrics-store-v2.e2e.test.ts index 271bd4bb18..5afb48edcb 100644 --- a/src/test/e2e/stores/client-metrics-store-v2.e2e.test.ts +++ b/src/test/e2e/stores/client-metrics-store-v2.e2e.test.ts @@ -5,6 +5,7 @@ import { IClientMetricsEnv, IClientMetricsStoreV2, } from '../../../lib/types/stores/client-metrics-store-v2'; +import { roundDownToHour } from '../../../lib/db/client-metrics-store-v2'; let db; let stores: IUnleashStores; @@ -382,3 +383,15 @@ test('Should not exists after delete', async () => { const existAfter = await clientMetricsStore.exists(metric); expect(existAfter).toBe(false); }); + +test('should floor hours as expected', () => { + expect( + roundDownToHour(new Date('2019-11-12T08:44:32.499Z')).toISOString(), + ).toBe('2019-11-12T08:00:00.000Z'); + expect( + roundDownToHour(new Date('2019-11-12T08:59:59.999Z')).toISOString(), + ).toBe('2019-11-12T08:00:00.000Z'); + expect( + roundDownToHour(new Date('2019-11-12T09:01:00.999Z')).toISOString(), + ).toBe('2019-11-12T09:00:00.000Z'); +});