Commit cba1fc90 authored by Savas Vedova's avatar Savas Vedova Committed by Olena Horal-Koretska

Extract differenceInMilliseconds datetime function

- Replace manual date usages with this utility function
- Remove DAY_IN_MS constant in favor of the existing one
- Update tests
parent 8691c13a
import { deprecatedCreateFlash as flash } from '~/flash'; import { deprecatedCreateFlash as flash } from '~/flash';
import { s__, sprintf } from '~/locale'; import { s__, sprintf } from '~/locale';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
// Renders math using KaTeX in any element with the // Renders math using KaTeX in any element with the
// `js-render-math` class // `js-render-math` class
...@@ -111,7 +112,7 @@ class SafeMathRenderer { ...@@ -111,7 +112,7 @@ class SafeMathRenderer {
// Give the browser time to reflow the svg // Give the browser time to reflow the svg
waitForReflow(() => { waitForReflow(() => {
const deltaTime = Date.now() - this.startTime; const deltaTime = differenceInMilliseconds(this.startTime);
this.totalMS += deltaTime; this.totalMS += deltaTime;
this.renderElement(); this.renderElement();
......
...@@ -216,8 +216,9 @@ export const timeFor = (time, expiredLabel) => { ...@@ -216,8 +216,9 @@ export const timeFor = (time, expiredLabel) => {
return timeago.format(time, `${timeagoLanguageCode}-remaining`).trim(); return timeago.format(time, `${timeagoLanguageCode}-remaining`).trim();
}; };
export const millisecondsPerDay = 1000 * 60 * 60 * 24;
export const getDayDifference = (a, b) => { export const getDayDifference = (a, b) => {
const millisecondsPerDay = 1000 * 60 * 60 * 24;
const date1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()); const date1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const date2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()); const date2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
...@@ -709,7 +710,7 @@ export const dateFromParams = (year, month, day) => { ...@@ -709,7 +710,7 @@ export const dateFromParams = (year, month, day) => {
* A utility function which computes the difference in seconds * A utility function which computes the difference in seconds
* between 2 dates. * between 2 dates.
* *
* @param {Date} startDate the start sate * @param {Date} startDate the start date
* @param {Date} endDate the end date * @param {Date} endDate the end date
* *
* @return {Int} the difference in seconds * @return {Int} the difference in seconds
...@@ -717,3 +718,18 @@ export const dateFromParams = (year, month, day) => { ...@@ -717,3 +718,18 @@ export const dateFromParams = (year, month, day) => {
export const differenceInSeconds = (startDate, endDate) => { export const differenceInSeconds = (startDate, endDate) => {
return (endDate.getTime() - startDate.getTime()) / 1000; return (endDate.getTime() - startDate.getTime()) / 1000;
}; };
/**
* A utility function which computes the difference in milliseconds
* between 2 dates.
*
* @param {Date|Int} startDate the start date. Can be either a date object or a unix timestamp.
* @param {Date|Int} endDate the end date. Can be either a date object or a unix timestamp. Defaults to now.
*
* @return {Int} the difference in milliseconds
*/
export const differenceInMilliseconds = (startDate, endDate = Date.now()) => {
const startDateInMS = startDate instanceof Date ? startDate.getTime() : startDate;
const endDateInMS = endDate instanceof Date ? endDate.getTime() : endDate;
return endDateInMS - startDateInMS;
};
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
export default (fn, { interval = 2000, timeout = 60000 } = {}) => { export default (fn, { interval = 2000, timeout = 60000 } = {}) => {
const startTime = Date.now(); const startTime = Date.now();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg)); const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
const next = () => { const next = () => {
if (timeout === 0 || Date.now() - startTime < timeout) { if (timeout === 0 || differenceInMilliseconds(startTime) < timeout) {
setTimeout(fn.bind(null, next, stop), interval); setTimeout(fn.bind(null, next, stop), interval);
} else { } else {
reject(new Error('SIMPLE_POLL_TIMEOUT')); reject(new Error('SIMPLE_POLL_TIMEOUT'));
......
...@@ -4,10 +4,13 @@ import { GlSparklineChart } from '@gitlab/ui/dist/charts'; ...@@ -4,10 +4,13 @@ import { GlSparklineChart } from '@gitlab/ui/dist/charts';
import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue'; import SeverityBadge from 'ee/vue_shared/security_reports/components/severity_badge.vue';
import { s__, sprintf } from '~/locale'; import { s__, sprintf } from '~/locale';
import { firstAndLastY } from '~/lib/utils/chart_utils'; import { firstAndLastY } from '~/lib/utils/chart_utils';
import { formatDate } from '~/lib/utils/datetime_utility'; import {
formatDate,
differenceInMilliseconds,
millisecondsPerDay,
} from '~/lib/utils/datetime_utility';
import { formattedChangeInPercent } from '~/lib/utils/number_utils'; import { formattedChangeInPercent } from '~/lib/utils/number_utils';
import ChartButtons from './vulnerability_chart_buttons.vue'; import ChartButtons from './vulnerability_chart_buttons.vue';
import { DAY_IN_MS } from '../store/modules/vulnerabilities/constants';
import { SEVERITY_LEVELS } from '../store/constants'; import { SEVERITY_LEVELS } from '../store/constants';
const ISO_DATE = 'isoDate'; const ISO_DATE = 'isoDate';
...@@ -74,7 +77,7 @@ export default { ...@@ -74,7 +77,7 @@ export default {
}, },
computed: { computed: {
startDate() { startDate() {
return Date.now() - DAY_IN_MS * this.vulnerabilitiesHistoryDayRange; return differenceInMilliseconds(millisecondsPerDay * this.vulnerabilitiesHistoryDayRange);
}, },
endDateCursor() { endDateCursor() {
return Date.now(); return Date.now();
......
...@@ -9,10 +9,10 @@ import { s__, sprintf } from '~/locale'; ...@@ -9,10 +9,10 @@ import { s__, sprintf } from '~/locale';
import { firstAndLastY } from '~/lib/utils/chart_utils'; import { firstAndLastY } from '~/lib/utils/chart_utils';
import { formattedChangeInPercent } from '~/lib/utils/number_utils'; import { formattedChangeInPercent } from '~/lib/utils/number_utils';
import { differenceInMilliseconds, millisecondsPerDay } from '~/lib/utils/datetime_utility';
import ChartButtons from './vulnerability_chart_buttons.vue'; import ChartButtons from './vulnerability_chart_buttons.vue';
import { DAY_IN_MS, DAYS } from '../store/modules/vulnerabilities/constants'; import { DAYS } from '../store/modules/vulnerabilities/constants';
import { SEVERITY_LEVELS } from '../store/constants'; import { SEVERITY_LEVELS } from '../store/constants';
export default { export default {
...@@ -74,7 +74,7 @@ export default { ...@@ -74,7 +74,7 @@ export default {
}); });
}, },
startDate() { startDate() {
return Date.now() - DAY_IN_MS * this.vulnerabilitiesHistoryDayRange; return differenceInMilliseconds(millisecondsPerDay * this.vulnerabilitiesHistoryDayRange);
}, },
dateInfo() { dateInfo() {
const formattedStartDate = dateFormat(this.startDate, 'mmmm dS'); const formattedStartDate = dateFormat(this.startDate, 'mmmm dS');
......
...@@ -8,8 +8,6 @@ export const INFO = 'info'; ...@@ -8,8 +8,6 @@ export const INFO = 'info';
export const UNKNOWN = 'unknown'; export const UNKNOWN = 'unknown';
export const SEVERITIES = [CRITICAL, HIGH, MEDIUM, LOW, INFO, UNKNOWN]; export const SEVERITIES = [CRITICAL, HIGH, MEDIUM, LOW, INFO, UNKNOWN];
export const DAY_IN_MS = 1000 * 60 * 60 * 24;
export const DAYS = { export const DAYS = {
THIRTY: 30, THIRTY: 30,
SIXTY: 60, SIXTY: 60,
......
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import { GlPopover, GlLink, GlIcon } from '@gitlab/ui'; import { GlPopover, GlLink, GlIcon } from '@gitlab/ui';
import GeoNodeLastUpdated from 'ee/geo_nodes/components/geo_node_last_updated.vue'; import GeoNodeLastUpdated from 'ee/geo_nodes/components/geo_node_last_updated.vue';
import { import {
HELP_NODE_HEALTH_URL, HELP_NODE_HEALTH_URL,
GEO_TROUBLESHOOTING_URL, GEO_TROUBLESHOOTING_URL,
STATUS_DELAY_THRESHOLD_MS, STATUS_DELAY_THRESHOLD_MS,
} from 'ee/geo_nodes/constants'; } from 'ee/geo_nodes/constants';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('GeoNodeLastUpdated', () => { describe('GeoNodeLastUpdated', () => {
let wrapper; let wrapper;
const staleStatusTime = new Date(Date.now() - STATUS_DELAY_THRESHOLD_MS).getTime(); const staleStatusTime = differenceInMilliseconds(STATUS_DELAY_THRESHOLD_MS);
const nonStaleStatusTime = new Date().getTime(); const nonStaleStatusTime = new Date().getTime();
const defaultProps = { const defaultProps = {
......
import { shallowMount } from '@vue/test-utils'; import { shallowMount } from '@vue/test-utils';
import TimeAgo from 'ee/vue_shared/dashboards/components/time_ago.vue'; import TimeAgo from 'ee/vue_shared/dashboards/components/time_ago.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('time ago component', () => { describe('time ago component', () => {
let wrapper; let wrapper;
...@@ -7,7 +8,7 @@ describe('time ago component', () => { ...@@ -7,7 +8,7 @@ describe('time ago component', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallowMount(TimeAgo, { wrapper = shallowMount(TimeAgo, {
propsData: { propsData: {
time: new Date(Date.now() - 86400000).toISOString(), time: new Date(differenceInMilliseconds(86400000)).toISOString(),
tooltipText: 'Finished', tooltipText: 'Finished',
}, },
}); });
......
import { TEST_HOST } from 'spec/test_constants'; import { TEST_HOST } from 'spec/test_constants';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
const AVATAR_URL = `${TEST_HOST}/dummy.jpg`; const AVATAR_URL = `${TEST_HOST}/dummy.jpg`;
...@@ -21,7 +22,7 @@ export const mockHeaders = { ...@@ -21,7 +22,7 @@ export const mockHeaders = {
export function mockPipelineData( export function mockPipelineData(
status = 'success', status = 'success',
id = 1, id = 1,
finishedTimeStamp = new Date(Date.now() - 86400000).toISOString(), finishedTimeStamp = new Date(differenceInMilliseconds(86400000)).toISOString(),
isTag = false, isTag = false,
) { ) {
return { return {
......
...@@ -3,7 +3,7 @@ import { format } from 'timeago.js'; ...@@ -3,7 +3,7 @@ import { format } from 'timeago.js';
import EnvironmentItem from '~/environments/components/environment_item.vue'; import EnvironmentItem from '~/environments/components/environment_item.vue';
import PinComponent from '~/environments/components/environment_pin.vue'; import PinComponent from '~/environments/components/environment_pin.vue';
import DeleteComponent from '~/environments/components/environment_delete.vue'; import DeleteComponent from '~/environments/components/environment_delete.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
import { environment, folder, tableData } from './mock_data'; import { environment, folder, tableData } from './mock_data';
describe('Environment item', () => { describe('Environment item', () => {
...@@ -135,7 +135,7 @@ describe('Environment item', () => { ...@@ -135,7 +135,7 @@ describe('Environment item', () => {
}); });
describe('in the past', () => { describe('in the past', () => {
const pastDate = new Date(Date.now() - 100000); const pastDate = new Date(differenceInMilliseconds(100000));
beforeEach(() => { beforeEach(() => {
factory({ factory({
propsData: { propsData: {
......
...@@ -653,3 +653,17 @@ describe('differenceInSeconds', () => { ...@@ -653,3 +653,17 @@ describe('differenceInSeconds', () => {
expect(datetimeUtility.differenceInSeconds(startDate, endDate)).toBe(expected); expect(datetimeUtility.differenceInSeconds(startDate, endDate)).toBe(expected);
}); });
}); });
describe('differenceInMilliseconds', () => {
const startDateTime = new Date('2019-07-17T00:00:00.000Z');
it.each`
startDate | endDate | expected
${startDateTime.getTime()} | ${new Date('2019-07-17T00:00:00.000Z')} | ${0}
${startDateTime} | ${new Date('2019-07-17T12:00:00.000Z').getTime()} | ${43200000}
${startDateTime} | ${new Date('2019-07-18T00:00:00.000Z').getTime()} | ${86400000}
${new Date('2019-07-18T00:00:00.000Z')} | ${startDateTime.getTime()} | ${-86400000}
`('returns $expected for $endDate - $startDate', ({ startDate, endDate, expected }) => {
expect(datetimeUtility.differenceInMilliseconds(startDate, endDate)).toBe(expected);
});
});
...@@ -5,6 +5,7 @@ import { Blob, BinaryBlob } from 'jest/blob/components/mock_data'; ...@@ -5,6 +5,7 @@ import { Blob, BinaryBlob } from 'jest/blob/components/mock_data';
import waitForPromises from 'helpers/wait_for_promises'; import waitForPromises from 'helpers/wait_for_promises';
import DeleteSnippetMutation from '~/snippets/mutations/deleteSnippet.mutation.graphql'; import DeleteSnippetMutation from '~/snippets/mutations/deleteSnippet.mutation.graphql';
import SnippetHeader from '~/snippets/components/snippet_header.vue'; import SnippetHeader from '~/snippets/components/snippet_header.vue';
import { differenceInMilliseconds } from '~/lib/utils/datetime_utility';
describe('Snippet header component', () => { describe('Snippet header component', () => {
let wrapper; let wrapper;
...@@ -67,7 +68,7 @@ describe('Snippet header component', () => { ...@@ -67,7 +68,7 @@ describe('Snippet header component', () => {
name: 'Thor Odinson', name: 'Thor Odinson',
}, },
blobs: [Blob], blobs: [Blob],
createdAt: new Date(Date.now() - 32 * 24 * 3600 * 1000).toISOString(), createdAt: new Date(differenceInMilliseconds(32 * 24 * 3600 * 1000)).toISOString(),
}; };
mutationVariables = { mutationVariables = {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment