@coolgk/cache
a javascript / typescript module
npm install @coolgk/cache
a redis wrapper
Examples
import { Cache } from '@coolgk/cache';
import { createClient } from 'redis';
const client = createClient({
host: 'localhost',
port: 12869,
password: '----'
});
const cache = new Cache({
redisClient: client
});
cache.set('abc', {a: 1}, 1).then(console.log);
cache.get('abc').then(console.log);
setTimeout(() => {
cache.get('abc').then(console.log);
client.quit();
}, 1500);
cache.getSetIfNull(
'abc',
() => Promise.resolve('data'),
10
).then((v) => {
console.log(v);
});
Promise.all([
cache.set('x', 'val x'),
cache.set('y', 'val y'),
cache.set('z', 'val z')
]).then(
() => Promise.all([
cache.get('x').then(console.log),
cache.get('y').then(console.log),
cache.get('z').then(console.log)
])
).then(
() => Promise.all([
cache.delete('x'),
cache.delete('y'),
cache.delete('z')
])
).then(
() => Promise.all([
cache.get('x').then(console.log),
cache.get('y').then(console.log),
cache.get('z').then(console.log)
])
);
Cache
Kind: global class
new Cache(options)
Param | Type | Description |
---|
options | object | |
[options.redisClient] | object | redis client from redis.createClient() redisClient needs to be passed in so the same connection can be used elsewhere and get closed outside this class |
cache.set(name, value, [expiry]) ⇒ promise
Kind: instance method of Cache
Param | Type | Default | Description |
---|
name | string | | name of the variable |
value | * | | value is always JSON.stringify'ed |
[expiry] | number | 0 | expire time in seconds. 0 = never expire |
cache.get(name) ⇒ promise
Kind: instance method of Cache
Returns: promise
- - cached value
Param | Type | Description |
---|
name | string | name of the variable |
cache.delete(name) ⇒ promise
Kind: instance method of Cache
Param | Type | Description |
---|
name | string | Array.<string> | name(s) of the variable |
cache.getSetIfNull(name, callback, [expiry]) ⇒ promise
get the cached value, if not set, resolve "callback()" and save the value then return it
Kind: instance method of Cache
Returns: promise
- - cached value
Param | Type | Default | Description |
---|
name | string | | name of the variable |
callback | function | | a callback function which returns a value or a promise |
[expiry] | number | 0 | expire time in seconds. 0 = never expire |
cache.command(command, ...params) ⇒ promise
Kind: instance method of Cache
Param | Type | Description |
---|
command | string | redis command to run |
...params | array | params for the command |