From 9c64a63d539ddaf9d7d9809d790a45f4f60db236 Mon Sep 17 00:00:00 2001 From: Tom Forbes Date: Tue, 23 Jan 2024 09:18:22 +0000 Subject: [PATCH] Fix numeric storage `expires` (#1099) * Fix numeric storage expiries * lint * === * changeset * always store as string * extra test for string --- .changeset/funny-jars-pump.md | 5 +++++ .../@guardian/libs/src/storage/storage.test.ts | 18 +++++++++++++++++- libs/@guardian/libs/src/storage/storage.ts | 7 +++++-- 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 .changeset/funny-jars-pump.md diff --git a/.changeset/funny-jars-pump.md b/.changeset/funny-jars-pump.md new file mode 100644 index 000000000..279bd05db --- /dev/null +++ b/.changeset/funny-jars-pump.md @@ -0,0 +1,5 @@ +--- +'@guardian/libs': patch +--- + +Make Storage handle numeric expiry value diff --git a/libs/@guardian/libs/src/storage/storage.test.ts b/libs/@guardian/libs/src/storage/storage.test.ts index 415bff2e4..78ef83ee9 100644 --- a/libs/@guardian/libs/src/storage/storage.test.ts +++ b/libs/@guardian/libs/src/storage/storage.test.ts @@ -78,7 +78,7 @@ 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(); @@ -86,6 +86,22 @@ describe.each([ 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(); diff --git a/libs/@guardian/libs/src/storage/storage.ts b/libs/@guardian/libs/src/storage/storage.ts index 9e950bceb..7c302a93a 100644 --- a/libs/@guardian/libs/src/storage/storage.ts +++ b/libs/@guardian/libs/src/storage/storage.ts @@ -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; } @@ -59,7 +62,7 @@ class StorageFactory { key, JSON.stringify({ value, - expires, + expires: expires ? new Date(expires) : undefined, }), ); }