Skip to content

Commit e6cf92f

Browse files
committed
adding in function for getTtlFromExpires
1 parent 1e09352 commit e6cf92f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

packages/cacheable/src/ttl.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
export function getTtlFromExpires(expires: number | undefined): number | undefined {
3+
if (expires === undefined) {
4+
return undefined;
5+
}
6+
7+
const now = Date.now();
8+
if (expires < now) {
9+
return undefined;
10+
}
11+
12+
return expires - now;
13+
}

packages/cacheable/test/ttl.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {test, expect} from 'vitest';
22
import {faker} from '@faker-js/faker';
33
import {Cacheable} from '../src/index.js';
4+
import {getTtlFromExpires} from '../src/ttl.js';
45
import {sleep} from './sleep.js';
56

67
test('should set a value with ttl', async () => {
@@ -22,3 +23,22 @@ test('should set a ttl on parameter', {timeout: 2000}, async () => {
2223
const result = await cacheable.get('key');
2324
expect(result).toEqual('value');
2425
});
26+
27+
test('should get the ttl from expires', () => {
28+
const now = Date.now();
29+
const expires = now + 1000;
30+
const result = getTtlFromExpires(expires);
31+
expect(result).toBe(1000);
32+
});
33+
34+
test('should get undefined when expires is undefined', () => {
35+
const result = getTtlFromExpires(undefined);
36+
expect(result).toBeUndefined();
37+
});
38+
39+
test('should get undefined when expires is in the past', () => {
40+
const now = Date.now();
41+
const expires = now - 1000;
42+
const result = getTtlFromExpires(expires);
43+
expect(result).toBeUndefined();
44+
});

0 commit comments

Comments
 (0)