1.1.0 • Published 4 years ago
@locmod/cache v1.1.0
Cache
This library enhances memory-cache module with Typescript support.
Installation
npm install --save @locmod/cache
Usage
import cache from '@locmod/cache'cache.set
(key: string, data: any, cacheAge?: number) => voidSaves the cache for specific amount of time in ms. If there is undefined, cache will be stored indefinitely.
cache.set('key1', { foo: 'bar' })
cache.set('key2', [1, 2, 3])
cache.set('key3', 'foo', 1000) // 1 secondcache.get
<T>(key: string) => T | nullGets the saved cache if there is any.
If no cache saved for this key, or it's expired, null will be returned. Supports generic types
cache.get('key1') // { foo: 'bar' }
cache.get<number[]>('key2') // [1, 2, 3]
cache.get<string>('key3') // 'foo'
setTimeout(() => {
cache.get<string>('key3') // null
}, 2000)cache.keys
() => string[]Returns all the saved keys
cache.keys() // ['key1', 'key2', 'key3']cache.clear
(key: string) => voidRemoves the saved key
cache.set('foo', 'bar')
cache.get('foo') // bar
cache.clear('foo')
cache.get('foo') // nullcache.clearMatch
(pattern: string) => voidRemoves all the saved keys that matches the pattern
cache.set('match-1', 'bar')
cache.set('match-2', 'bar')
cache.set('match-3', 'bar')
cache.set('foo', 'bar')
cache.clearMatch('match-')
cache.get('match-1') // null
cache.get('match-2') // null
cache.get('match-3') // null
cache.get('foo') // barcache.clearAll
() => voidRemoves the saved keys
cache.set('match-1', 'bar')
cache.set('match-2', 'bar')
cache.set('match-3', 'bar')
cache.set('foo', 'bar')
cache.clearAll('match-')
cache.get('match-1') // null
cache.get('match-2') // null
cache.get('match-3') // null
cache.get('foo') // null