Skip to content

Commit

Permalink
fix: correctly calculate the start of the next minute (#73)
Browse files Browse the repository at this point in the history
* fix: correctly calculate the start of the next minute

* fix
  • Loading branch information
braaar authored Dec 19, 2023
1 parent 72fdc01 commit f35433a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
17 changes: 17 additions & 0 deletions src/abax-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { addMilliseconds } from 'date-fns';
import { type Interceptable, MockAgent, setGlobalDispatcher } from 'undici';
import { beforeEach, describe, expect, it } from 'vitest';
import { AbaxClient } from './main.js';
Expand Down Expand Up @@ -32,6 +33,14 @@ describe('abax-client', () => {
})
.reply(() => ({
statusCode: 429,
responseOptions: {
headers: {
'X-Rate-Limit-Reset': addMilliseconds(
new Date(),
100,
).toISOString(),
},
},
}))
.times(4);

Expand All @@ -50,6 +59,14 @@ describe('abax-client', () => {
})
.reply(() => ({
statusCode: 429,
responseOptions: {
headers: {
'X-Rate-Limit-Reset': addMilliseconds(
new Date(),
100,
).toISOString(),
},
},
}))
.times(3);

Expand Down
11 changes: 11 additions & 0 deletions src/common/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { describe, expect, it } from 'vitest';
import { startOfTheNextMinute } from '../utils';

describe('utils', () => {
it('should get the start of the next minute correctly', () => {
const now = new Date('2023-01-01T16:47:36.351Z');
const next = startOfTheNextMinute(now);

expect(next.toISOString()).toBe('2023-01-01T16:48:00.000Z');
});
});
17 changes: 10 additions & 7 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addMinutes, setMilliseconds, setSeconds } from 'date-fns';
import { addMinutes, set } from 'date-fns';
import type { z } from 'zod';

export function withZod<T extends z.ZodTypeAny, Output = z.infer<T>>(
Expand Down Expand Up @@ -43,10 +43,13 @@ export function makeBody(data: {
return params;
}

export function startOfTheNextMinute(): Date {
const now = new Date();
addMinutes(now, 1);
setSeconds(now, 0);
setMilliseconds(now, 0);
return now;
export function startOfTheNextMinute(fromDate?: Date): Date {
const now = fromDate ?? new Date();

const zeroSeconds = set(now, {
seconds: 0,
milliseconds: 0,
});

return addMinutes(zeroSeconds, 1);
}

0 comments on commit f35433a

Please sign in to comment.