Skip to content

Commit

Permalink
feat: lru-cache driver (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Feb 6, 2023
1 parent 41ffcf4 commit 03dfb2e
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 0 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,21 @@ const storage = createStorage({
});
```

### `lru-cache` (universal)

Keeps cached data in memory using [LRU Cache](https://www.npmjs.com/package/lru-cache).

See [`lru-cache`](https://www.npmjs.com/package/lru-cache) for supported options. By default `{ maxSize: 500 }` is used.

```js
import { createStorage } from "unstorage";
import lruCacheDriver from "unstorage/drivers/lru-cache";

const storage = createStorage({
driver: lruCacheDriver(),
});
```

### `overlay` (universal)

This is a special driver that creates a multi-layer overlay driver.
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"h3": "^1.1.0",
"ioredis": "^5.3.0",
"listhen": "^1.0.2",
"lru-cache": "^7.14.1",
"mkdir": "^0.0.2",
"mri": "^1.2.0",
"node-fetch-native": "^1.0.1",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 42 additions & 0 deletions src/drivers/lru-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { defineDriver } from "./utils";
import LRU, { SharedOptions as _LRUOptions } from "lru-cache";

type LRUOptions = _LRUOptions<string, any>;
export interface LRUDriverOptions extends LRUOptions {}

export default defineDriver((opts: LRUDriverOptions) => {
const cache = new LRU({
...opts,
maxSize: 500,
});

return {
hasItem(key) {
return cache.has(key);
},
getItem(key) {
return cache.get(key) || null;
},
getItemRaw(key) {
return cache.get(key) || null;
},
setItem(key, value) {
cache.set(key, value);
},
setItemRaw(key, value) {
cache.set(key, value);
},
removeItem(key) {
cache.delete(key);
},
getKeys() {
return Array.from(cache.keys());
},
clear() {
cache.clear();
},
dispose() {
cache.clear();
},
};
});
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const builtinDrivers = {
github: "unstorage/drivers/github",
http: "unstorage/drivers/http",
localStorage: "unstorage/drivers/localstorage",
lruCache: "unstorage/drivers/lru-cache",
localstorage: "unstorage/drivers/localstorage",
memory: "unstorage/drivers/memory",
overlay: "unstorage/drivers/overlay",
Expand Down

0 comments on commit 03dfb2e

Please sign in to comment.