Skip to content

Commit

Permalink
Fix numeric storage expires (#1099)
Browse files Browse the repository at this point in the history
* Fix numeric storage expiries

* lint

* ===

* changeset

* always store as string

* extra test for string
  • Loading branch information
tomrf1 authored Jan 23, 2024
1 parent ecee45c commit 9c64a63
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/funny-jars-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@guardian/libs': patch
---

Make Storage handle numeric expiry value
18 changes: 17 additions & 1 deletion libs/@guardian/libs/src/storage/storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,30 @@ describe.each([
expect(implementation.get('thisDoesNotExist')).toBeNull();
});

it(`does not return an expired item`, () => {
it(`does not return an expired item with expiry as Date object`, () => {
implementation.set('iAmExpired', 'data', new Date('1901-01-01'));
expect(implementation.get('iAmExpired')).toBeNull();

// check it's been deleted too
expect(native.getItem('iAmExpired')).toBeNull();
});

it(`does not return an expired item with expiry as numeric value (millis since epoch)`, () => {
implementation.set('iAmExpired', 'data', new Date('1901-01-01').getTime());
expect(implementation.get('iAmExpired')).toBeNull();

// check it's been deleted too
expect(native.getItem('iAmExpired')).toBeNull();
});

it(`does not return an expired item with expiry as ISO date string`, () => {
implementation.set('iAmExpired', 'data', '1901-01-01T00:00:00.000Z');
expect(implementation.get('iAmExpired')).toBeNull();

// check it's been deleted too
expect(native.getItem('iAmExpired')).toBeNull();
});

it(`return null for a malformed item`, () => {
native.setItem('malformed', '[]');
expect(implementation.get('malformed')).toBeNull();
Expand Down
7 changes: 5 additions & 2 deletions libs/@guardian/libs/src/storage/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ class StorageFactory {
const { value, expires } = data;

// is this item has passed its sell-by-date, remove it
if (isString(expires) && new Date() > new Date(expires)) {
if (
(isString(expires) || typeof expires === 'number') &&
new Date() > new Date(expires)
) {
this.remove(key);
return null;
}
Expand All @@ -59,7 +62,7 @@ class StorageFactory {
key,
JSON.stringify({
value,
expires,
expires: expires ? new Date(expires) : undefined,
}),
);
}
Expand Down

0 comments on commit 9c64a63

Please sign in to comment.