Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'cache-manager' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
before(function () {
redisCacheByUrl = require('cache-manager').caching({
store: redisStore,
// redis://[:password@]host[:port][/db-number][?option=value]
url: 'redis://:' + config.redis.auth_pass + '@' + config.redis.host + ':' + config.redis.port + '/' + config.redis.db + '?ttl=' + config.redis.ttl,
// some fakes to see that url overrides them
host: 'test-host',
port: -78,
db: -7,
auth_pass: 'test_pass',
password: 'test_pass',
ttl: -6,
compress: true
});
});
// @flow
import cacheManager from 'cache-manager';
import type { Cache } from 'cache-manager';
const memoryCache: Cache = new cacheManager.caching({
store: 'memory', max: 100, ttl: 10
});
// $ExpectError store missing
const invalidMemoryCache: Cache = new cacheManager.caching({
max: 200,
});
// $ExpectError
const invalidMemoryCache2: Cache = new cacheManager.caching({ max: '200' });
(memoryCache.set('foo', 'bar', { ttl: 5 }): Promise);
// $ExpectError Wrong Promise return
(memoryCache.set('foo', 'bar', { ttl: 5 }): Promise);
memoryCache.get('foo');
// FIXME: move this to a test helper that can be used by other apps
import cacheManager from 'cache-manager'
import { Application, ApplicationFunction } from '../../src'
const cache = cacheManager.caching({ store: 'memory', ttl: 0 })
export function newApp (): Application {
return new Application({ app: {
getInstallationAccessToken: jest.fn().mockResolvedValue('test'),
getSignedJsonWebToken: jest.fn().mockReturnValue('test')
}, cache })
}
export function createApp (appFn?: ApplicationFunction) {
const app = newApp()
appFn && appFn(app)
return app
}
/*
var redisStore = require('cache-manager-redis');
var redisCacheConfig = {
store: redisStore,
host: 'localhost', // default value
port: 6379, // default value
auth_pass: '',
db: 0,
ttl: TTL,
promiseDependency: Promise
};
var cacheStore = cacheManager.multiCaching([cacheManager.caching(redisCacheConfig)]);
*/
// comment if using another store
var cacheStore = cacheManager.multiCaching([cacheManager.caching({
store: 'memory',
max: 2 * BIG_NUMBERS_LIST.length,
ttl: TTL
})]);
var phoneUtilsBase = require('../../../lib');
var DEFAULT_PORT = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var winston = require('winston');
var LOG_LEVEL = 'debug';
winston.level = LOG_LEVEL;
var winstonHlrLookupLogger = new winston.Logger({
max: 0,
ttl: 0
};
}
// force 0 ttl
cacheOpts.ttl = 0;
console.log("store options: %j", cacheOpts);
switch (cacheOpts.store) {
case "redis":
cacheOpts.store = redisStore;
break;
}
var cache = cacheManager.caching(cacheOpts);
function set(key, val, ttl = 0) {
ttl = Math.floor(ttl);
return new Promise((resolve, reject) => {
cache.set(key, val, { ttl: ttl }, err => {
if (err) {
reject(err);
}
resolve();
});
});
}
function get(key) {
return new Promise((resolve, reject) => {
cache.get(key, (err, result) => {
import config from 'config';
import extend from 'extend';
import logger from 'logger';
import redisStore from 'cache-manager-redis';
// level 2 cache - redis
let redisConfig = extend({}, config.caching.redis, { store: redisStore });
let redisCache = cacheManager.caching(redisConfig);
redisCache.store.events.on('redisError', function onRedisCacheError(error) {
logger.error(error);
});
// level 1 cache - memory
let memoryConfig = extend({}, config.caching.memory, { store: 'memory' });
let memoryCache = cacheManager.caching(memoryConfig);
// cache hierarchy wrapper
let multiCache = cacheManager.multiCaching([ memoryCache, redisCache ]);
export default multiCache;
const self = this;
let { config } = settings;
config = config || {};
// make a copy before merging the config into the defaultConfig
const ttlConfig = extend(true, {}, config.ttl);
this._config = Object.assign({}, defaultConfig, config);
extend(true, this._config.ttl, defaultConfig.ttl, ttlConfig);
this.__setDB(settings, this._config);
this._stores = settings.stores ? settings.stores : defaultStores;
if (this._stores.length > 1) {
this._stores = this._stores.map(store => nodeCacheManager.caching(store));
this._cacheManager = nodeCacheManager.multiCaching(this._stores);
this._stores.forEach(cache => {
self._redisClient = self._redisClient || checkRedis(cache);
});
if (self._redisClient) {
// We create a cacheManager instance without the Redis store
// so in queries we can target this instance even though we directy
// save into Redis client.
// See queries.read() method
const storeWithoutRedis = this._stores.filter(c => c.store.name !== 'redis');
this._cacheManagerNoRedis = nodeCacheManager.multiCaching(storeWithoutRedis);
}
} else {
this._cacheManager = nodeCacheManager.caching(this._stores[0]);
this._redisClient = this._redisClient || checkRedis(this._cacheManager);
const plugin = (fastify, opts, next) => {
opts = Object.assign({
stores: [CacheManager.caching({ store: 'memory', max: 1000, ttl: 30 })]
}, opts)
// creating multi-cache instance
const multiCache = CacheManager.multiCaching(opts.stores)
fastify.addHook('onRequest', (request, reply, next) => {
const { res } = reply
const { req } = request
onEnd(res, (payload) => {
// avoid double caching
if (req.cacheHit) return
if (payload.headers[X_CACHE_EXPIRE]) {
// support service level expiration
const keysPattern = payload.headers[X_CACHE_EXPIRE]
// delete keys on all cache tiers
opts.stores.forEach(cache => getKeys(cache, keysPattern).then(keys => multiCache.del(keys)))
} else if (payload.headers[X_CACHE_TIMEOUT]) {
// we need to cache response
import redisStore from 'cache-manager-redis';
// level 2 cache - redis
let redisConfig = extend({}, config.caching.redis, { store: redisStore });
let redisCache = cacheManager.caching(redisConfig);
redisCache.store.events.on('redisError', function onRedisCacheError(error) {
logger.error(error);
});
// level 1 cache - memory
let memoryConfig = extend({}, config.caching.memory, { store: 'memory' });
let memoryCache = cacheManager.caching(memoryConfig);
// cache hierarchy wrapper
let multiCache = cacheManager.multiCaching([ memoryCache, redisCache ]);
export default multiCache;
this._stores = settings.stores ? settings.stores : defaultStores;
if (this._stores.length > 1) {
this._stores = this._stores.map(store => nodeCacheManager.caching(store));
this._cacheManager = nodeCacheManager.multiCaching(this._stores);
this._stores.forEach(cache => {
self._redisClient = self._redisClient || checkRedis(cache);
});
if (self._redisClient) {
// We create a cacheManager instance without the Redis store
// so in queries we can target this instance even though we directy
// save into Redis client.
// See queries.read() method
const storeWithoutRedis = this._stores.filter(c => c.store.name !== 'redis');
this._cacheManagerNoRedis = nodeCacheManager.multiCaching(storeWithoutRedis);
}
} else {
this._cacheManager = nodeCacheManager.caching(this._stores[0]);
this._redisClient = this._redisClient || checkRedis(this._cacheManager);
/**
* If we *only* have a Redis store AND no ttl config has been passed
* we copy the default ttl config for "redis" to the "global" ttl
*/
if (this._redisClient && !config.ttl) {
this._config.ttl.keys = this._config.ttl.redis.keys;
this._config.ttl.queries = this._config.ttl.redis.queries;
}
}
this.__bindCacheManagerMethods();