-
Notifications
You must be signed in to change notification settings - Fork 0
Implement cache manager #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
c8f7808
Install dependencies ➕
ikovac d6f015b
Implement cache manager and providers ✨
ikovac 70608a0
Remove default LRU maxAge ♻️
ikovac 4c5ec6d
Add examples 📝
ikovac bc4f96b
Remove dev script 🔨
ikovac 644f82f
Remove nodemon package ➖
ikovac 5c9e1ea
Add MIT license 📄
ikovac 116f8b5
Update readme documentation 📝
ikovac 522e67b
Fix typos in readme ✏️
ikovac 3b031cb
Readme grammar correction ✏️
ikovac ccb520c
Add git repo to the package.json 📝
ikovac 3c86bd8
Fix typo in readme ✏️
ikovac 236df58
Install np package ➕
ikovac 6764348
Prune expired records ♻️
ikovac e7198cb
Fix package.json package files 🐛
ikovac a9a78f3
🔖
ikovac 8909f16
Add org prefix for package name 📦
ikovac d1141f4
Add publish access, edit author info 📦
ikovac 197f21c
Comment s to ms conversion 💡
ikovac 0148a86
Link example file in readme 📝
ikovac 90132d5
Assign default options to the options object ♻️
ikovac 88c1637
Order imports 🎨
ikovac 5ff23f2
Remove duplicate tests, refactor existing tests ✅
ikovac cd64831
Move mocks from test files 🚚
ikovac f2fa68f
Update readme, remove WIP, add import guide 📝
ikovac ed7e49a
Improve documentation 📝
ikovac 1551c77
Move default store value to defaultOptions ♻️
ikovac 3cd1227
📝
ikovac a91eaf0
Update tests ✅
ikovac 8b9ef65
Throw an error if key is not provided ♻️
ikovac b0f3bd4
Add cache manager set method tests ✅
ikovac 2f03f71
Remove name property 🔥
ikovac 6030267
Export providers from module 🏗
ikovac 6e8dbdb
Update test and example imports ✅ 📝
ikovac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| MIT License | ||
|
|
||
| Copyright (c) 2021 ExtensionEngine, LLC | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,98 @@ | ||
| Node cache manager | ||
| # Tapster | ||
| Cache adapter module for NodeJs. | ||
|
|
||
| ## Installation: | ||
| ``` | ||
| npm install @extensionengine/tapster | ||
| ``` | ||
| ```js | ||
| const { CacheManager } = require('@extensionengine/tapster'); | ||
| const cache = new CacheManager({ /* ... */ }); | ||
| ``` | ||
|
|
||
| ## Store providers | ||
| - `memory` (uses [LRU](https://github.com/isaacs/node-lru-cache)) | ||
| - `redis` (uses [ioredis](https://github.com/luin/ioredis)) | ||
| - custom - use any store you want, as long as it has the same API | ||
|
|
||
| ## Usage | ||
| See examples below and in the [examples](./examples) directory. | ||
|
|
||
| ### Memory store | ||
| ```js | ||
| const client = new CacheManager({ store: 'memory', ttl: 10 /* seconds */ }); | ||
|
|
||
| // If the set method is called without ttl, the default ttl will be used | ||
| await client.set('foo', 'bar'); | ||
| await client.get('foo'); // bar | ||
| await client.has('foo') // true | ||
| await client.has('baz'); // false | ||
|
|
||
| await sleep('10s'); | ||
| await client.get('foo'); // undefined | ||
| await client.has('foo') // false | ||
|
|
||
| // When ttl is defined, it will overwrite the default one | ||
| await client.set('foo', 'bar', 5); | ||
| await client.has('foo') // true | ||
|
|
||
| await sleep('5s'); | ||
| await client.has('foo') // false | ||
|
|
||
| // ttl = 0 means no expiration time | ||
| await client.set('foo', 'bar', 0); | ||
| ``` | ||
|
|
||
| ### Redis store | ||
| ```js | ||
| const client = new CacheManager({ | ||
| store: 'redis', | ||
| host: 'localhost', | ||
| port: 6379, | ||
| ttl: 10 /* seconds */ | ||
| }); | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| await client.get('foo'); // bar | ||
| ``` | ||
|
|
||
| ### Custom store | ||
| You can use your own custom store by creating one with the same API as the built-in memory stores (such as a memory or redis). See [example](./examples/custom-store.js). | ||
| ```js | ||
| class CustomStore { /* ... */ } | ||
| const client = new CacheManager({ store: CustomStore }); | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| await client.get('foo'); // bar | ||
| ``` | ||
| ## Options | ||
| ### Common | ||
| - `store` - built-in store (`memory`, `redis`) or custom store. | ||
| - `ttl` - time to live in seconds. | ||
| ### Redis store | ||
| - `host` (required) - redis host. | ||
| - `port` (required) - redis port. | ||
| - `password` (optional) - redis password. | ||
|
|
||
| ## API | ||
| - `set(key, value, ttl)` - TTL is optional. The cache manager instance's TTL will be used if the set method is called without a ttl parameter. | ||
| - `get(key) => value` | ||
| - `delete(key)` | ||
| - `has(key)` | ||
| - `getKeys(pattern) => keys` | ||
|
|
||
| Supported glob-style patterns: | ||
| - h?llo matches hello, hallo and hxllo | ||
| - h*llo matches hllo and heeeello | ||
| - h[ae]llo matches hello and hallo, but not hillo | ||
| - h[^e]llo matches hallo, hbllo, ... but not hello | ||
| - h[a-b]llo matches hallo and hbllo | ||
|
|
||
| ## Tests | ||
| To run tests run: | ||
| ``` | ||
| npm t | ||
| ``` | ||
|
|
||
| ## License | ||
| Tapster is licensed under the MIT license. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| 'use strict'; | ||
|
|
||
| const { CacheManager } = require('../lib'); | ||
|
|
||
| class Custom { | ||
| constructor() { | ||
| this.entries = {}; | ||
| } | ||
|
|
||
| set(key, value) { | ||
| return Promise.resolve(this.entries[key] = value); | ||
| } | ||
|
|
||
| get(key) { | ||
| return Promise.resolve(this.entries[key]); | ||
| } | ||
|
|
||
| has(key) { | ||
| return Promise.resolve(!!this.entries[key]); | ||
| } | ||
|
|
||
| delete(key) { | ||
| delete this.entries[key]; | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| getKeys() { | ||
| return Object.keys(this.entries); | ||
| } | ||
|
|
||
| static create() { | ||
| return new Custom(); | ||
| } | ||
| } | ||
|
|
||
| async function main() { | ||
| const client = new CacheManager({ store: Custom }); | ||
| await client.set('foo', 'bar'); | ||
| console.log(await client.get('foo')); // bar | ||
| console.log(await client.has('foo')); // true | ||
| console.log(await client.getKeys()); // ['foo'] | ||
| await client.delete('foo'); | ||
| console.log(await client.get('foo')); // undefined | ||
| } | ||
|
|
||
| main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| 'use strict'; | ||
|
|
||
| const { CacheManager } = require('../lib'); | ||
|
|
||
| async function example1() { | ||
| const client = new CacheManager(); // same as: new CacheManager({ store: 'memory' }); | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| console.log(await client.get('foo')); // bar | ||
| console.log(await client.has('foo')); // true | ||
| await client.delete('foo'); | ||
| console.log(await client.get('foo')); // undefined | ||
| console.log(await client.has('foo')); // false | ||
|
|
||
| await client.set('example-1', 'example'); | ||
| await client.set('example-2', 'example'); | ||
| await client.set('lorem', 'ipsum'); | ||
| await client.set('foo', 'bar'); | ||
| console.log(await client.getKeys()); // ['foo', 'lorem', 'example-2', 'example-1'] | ||
| console.log(await client.getKeys('*')); // ['foo', 'lorem', 'example-2', 'example-1'] | ||
| console.log(await client.getKeys('example-*')); // ['example-2', 'example-1'] | ||
| } | ||
|
|
||
| async function example2() { | ||
| const client = new CacheManager({ store: 'memory', ttl: 5 }); // ttl - time to live in seconds | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(6000); // sleep for 6000ms = 6s | ||
| console.log(await client.get('foo')); // undefined | ||
|
|
||
| const NO_EXPIRATION_TTL = 0; | ||
| await client.set('foo', 'bar', NO_EXPIRATION_TTL); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(5000); // sleep for 5000ms = 5s | ||
| console.log(await client.get('foo')); // bar | ||
|
|
||
| await client.set('foo', 'bar', 2); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(2000); // sleep for 2000ms = 2s | ||
| console.log(await client.get('foo')); // undefined | ||
| } | ||
|
|
||
| example1(); | ||
| example2(); | ||
|
|
||
| const sleep = time => new Promise(resolve => setTimeout(() => resolve(), time)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| 'use strict'; | ||
|
|
||
| const { CacheManager } = require('../lib'); | ||
|
|
||
| async function example1() { | ||
| const client = new CacheManager({ | ||
| store: 'redis', | ||
| host: 'localhost', | ||
| port: 6379 | ||
| }); | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| console.log(await client.get('foo')); // bar | ||
| console.log(await client.has('foo')); // true | ||
| await client.delete('foo'); | ||
| console.log(await client.get('foo')); // undefined | ||
| console.log(await client.has('foo')); // false | ||
|
|
||
| await client.set('example-1', 'example'); | ||
| await client.set('example-2', 'example'); | ||
| await client.set('lorem', 'ipsum'); | ||
| await client.set('foo', 'bar'); | ||
| console.log(await client.getKeys()); // ['foo', 'lorem', 'example-2', 'example-1'] | ||
| console.log(await client.getKeys('*')); // ['foo', 'lorem', 'example-2', 'example-1'] | ||
| console.log(await client.getKeys('example-*')); // ['example-2', 'example-1'] | ||
| } | ||
|
|
||
| async function example2() { | ||
| const client = new CacheManager({ | ||
| store: 'redis', | ||
| host: 'localhost', | ||
| port: 6379, | ||
| ttl: 5 // time to live in seconds | ||
| }); | ||
|
|
||
| await client.set('foo', 'bar'); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(6000); // sleep for 6000ms = 6s | ||
| console.log(await client.get('foo')); // undefined | ||
|
|
||
| const NO_EXPIRATION_TTL = 0; | ||
| await client.set('foo', 'bar', NO_EXPIRATION_TTL); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(5000); // sleep for 5000ms = 5s | ||
| console.log(await client.get('foo')); // bar | ||
|
|
||
| await client.set('foo', 'bar', 2); | ||
| console.log(await client.get('foo')); // bar | ||
| await sleep(2000); // sleep for 2000ms = 2s | ||
| console.log(await client.get('foo')); // undefined | ||
| } | ||
|
|
||
| example1(); | ||
| example2(); | ||
|
|
||
| const sleep = time => new Promise(resolve => setTimeout(() => resolve(), time)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| 'use strict'; | ||
|
|
||
| const autobind = require('auto-bind'); | ||
| const path = require('path'); | ||
| const providers = require('./providers'); | ||
|
|
||
| const defaultOptions = { store: 'memory', ttl: 0 }; | ||
|
|
||
| class CacheManager { | ||
| constructor(options) { | ||
| options = { ...defaultOptions, ...options }; | ||
| this.provider = CacheManager.createProvider(options); | ||
| autobind(this); | ||
ikovac marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| set(key, value, ttl) { | ||
| if (!key) return Promise.reject(new Error('Key must be defined')); | ||
| return this.provider.set(key, value, ttl); | ||
| } | ||
|
|
||
| get(key) { | ||
| return this.provider.get(key); | ||
| } | ||
|
|
||
| has(key) { | ||
| return this.provider.has(key); | ||
| } | ||
|
|
||
| getKeys(pattern = '*') { | ||
| return this.provider.getKeys(pattern); | ||
| } | ||
|
|
||
| delete(key) { | ||
| return this.provider.delete(key); | ||
| } | ||
|
|
||
| static createProvider({ store, ...options }) { | ||
| if (typeof store === 'string') { | ||
| return loadProvider(store).create(options); | ||
| } | ||
| return store.create(options); | ||
| } | ||
| } | ||
|
|
||
| module.exports = { CacheManager, providers }; | ||
|
|
||
| function loadProvider(name) { | ||
| try { | ||
| return require(path.join(__dirname, './providers/', name)); | ||
| } catch (err) { | ||
| if (err.code === 'MODULE_NOT_FOUND') throw new Error('Unsupported provider'); | ||
| throw err; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| const Memory = require('./memory'); | ||
| const Redis = require('./redis'); | ||
|
|
||
| module.exports = { Memory, Redis }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| 'use strict'; | ||
|
|
||
| const LRU = require('lru-cache'); | ||
| const micromatch = require('micromatch'); | ||
| const yup = require('yup'); | ||
|
|
||
| const schema = yup.object().shape({ | ||
| ttl: yup.number() | ||
| }); | ||
|
|
||
| class Memory { | ||
| constructor(config) { | ||
| config = schema.validateSync(config, { stripUnknown: true }); | ||
| this.ttl = config.ttl; | ||
| this.client = new LRU(); | ||
| } | ||
|
|
||
| set(key, value, ttl = this.ttl) { | ||
| return Promise.resolve( | ||
| this.client.set(key, value, ttl * 1000 /* convert seconds to milliseconds */) | ||
| ); | ||
| } | ||
|
|
||
| get(key) { | ||
| return Promise.resolve(this.client.get(key)); | ||
| } | ||
|
|
||
| has(key) { | ||
| return Promise.resolve(this.client.has(key)); | ||
| } | ||
|
|
||
| getKeys(pattern = '*') { | ||
| this.client.prune(); // Delete expired records | ||
| const keys = this.client.keys(); | ||
| return Promise.resolve(micromatch(keys, pattern)); | ||
| } | ||
|
|
||
| delete(key) { | ||
| return Promise.resolve(this.client.del(key)); | ||
| } | ||
|
|
||
| static create(config) { | ||
| return new Memory(config); | ||
| } | ||
| } | ||
|
|
||
| module.exports = Memory; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.