Skip to content

Commit

Permalink
Use chrome.alarms to purge cache where available (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Sep 9, 2020
1 parent d61d250 commit a2c38a0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
23 changes: 19 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,12 @@ async function deleteWithLogic(logic?: (x: CacheItem<Value>) => boolean): Promis
}
}

let lastRun = 0; // Homemade debouncing due to `chrome.alarms` potentially queueing this function
async function deleteExpired(): Promise<void> {
await deleteWithLogic(cachedItem => Date.now() > cachedItem.maxAge);
if (lastRun < Date.now() - 1000) {
lastRun = Date.now();
await deleteWithLogic(cachedItem => Date.now() > cachedItem.maxAge);
}
}

async function clear(): Promise<void> {
Expand Down Expand Up @@ -163,13 +167,24 @@ const cache = {
};

function init(): void {
// Make it available globally for ease of use
(window as any).webextStorageCache = cache;

// Automatically clear cache every day
if (isBackgroundPage()) {
if (!isBackgroundPage()) {
return;
}

if (chrome.alarms) {
chrome.alarms.create('webext-storage-cache', {
delayInMinutes: 1,
periodInMinutes: 60 * 24
});
chrome.alarms.onAlarm.addListener(deleteExpired);
} else {
setTimeout(deleteExpired, 60000); // Purge cache on launch, but wait a bit
setInterval(deleteExpired, 1000 * 3600 * 24);
}

(window as any).webextStorageCache = cache;
}

init();
Expand Down
19 changes: 13 additions & 6 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,21 @@ import storageCache from 'webext-storage-cache';

## Usage

This module requires the `storage` permission:
This module requires the `storage` permission and it’s suggested to also use `alarms` to safely schedule cache purging:

```json
// manifest.json
```json5
/* manifest.json */
{
"permissions": [
"storage"
]
"storage",
"alarms"
],
"background": {
"scripts": [
/* Remember to include/import it in the background to enable expired cache purging */
"webext-storage-cache.js"
]
}
}
```

Expand All @@ -45,7 +52,7 @@ import cache from 'webext-storage-cache';
})();
```

The same code could be also written more effectively with `cache.function`:
The same code could also be written more effectively with `cache.function`:

```js
import cache from 'webext-storage-cache';
Expand Down

0 comments on commit a2c38a0

Please sign in to comment.