How to use cache-manager - 10 common examples

To help you get started, we’ve selected a few cache-manager examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dial-once / node-cache-manager-redis / test / lib / redis-store-zlib-spec.js View on Github external
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
      });
    });
github flow-typed / flow-typed / definitions / npm / cache-manager_v2.x.x / test_cache-manager_v2.js View on Github external
// @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');
github probot / probot / test / apps / helper.ts View on Github external
// 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
}
github dial-once / node-phone-utils / tests / integration / helpers / server.js View on Github external
/*
 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({
github travisghansen / external-auth-server / src / store.js View on Github external
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) => {
github mcibique / express-security / server / helpers / caching.js View on Github external
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;
github sebelga / nsql-cache / lib / index.js View on Github external
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);
github jkyberneees / fastify-gateway / src / plugins / cache.js View on Github external
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
github mcibique / express-security / server / helpers / caching.js View on Github external
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;
github sebelga / nsql-cache / lib / index.js View on Github external
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();

cache-manager

Cache module for Node.js

MIT
Latest version published 11 days ago

Package Health Score

91 / 100
Full package analysis

Popular cache-manager functions