Cache is easy to use data caching Node.js package. It supports Memcached, Redis, and In-Memory caching engines.

Overview

Cache

Latest version

Cache NPM implements wrapper over multiple caching engines - Memcached, Redis and In-memory (use with single threaded process in development mode only). The decision of which caching engine to use is governed while creating the Cache NPM object.

Why Cache?

Core packages of different caching systems do not have a common interface, i.e. they have the same functionality implemented with different method signatures. Thus changing from one cache system to another becomes difficult as all the usages need to be revisited. This NPM package solves the problem by providing common wrapper methods for memcached, redis and in-memory caching systems.

Prerequisites

Required caching engine for the use case must be installed and up. Refer memcached and redis installation guide.

Installion

npm install @plgworks/cache --save

Initialize

const Cache = require('@plgworks/cache');

const configStrategy = {}; // Refer the next section for detailed documentation on configStrategy
const cache = Cache.getInstance(configStrategy);

const cacheImplementer = cache.cacheInstance;

Note: To print detailed logs, add CACHE_DEBUG_ENABLED = '1' in your env variables.

Config Strategy

configStrategy is a mandatory parameter which specifies the configuration strategy to be used for a particular cache engine.

An example of the configStrategy is:

const configStrategy = {
  cache: {
    engine: "none/redis/memcached",
    host: "",
    port: "",
    password: "",
    enableTsl: "",
    defaultTtl: 10000,
    consistentBehavior: "",
    servers:[],
    namespace: ""
  }
};
  • engine: redis, memcached are different types of caching engine. For in-memory cache engine parameter will be none.
  • host: Host of the redis caching engine.
  • port: Port on which redis caching engine is running.
  • password: Redis caching engine password.
  • enableTsl: This field is used to enable tsl.
  • defaultTtl: Default cache expiry time in sec.
  • consistentBehavior: This field is required to create cache instance key.
  • servers: servers is an array of memcached servers.
  • namespace: It is in-memory cache namespace.

Redis Example

Following is an example of redis engine config strategy to be used in initializing Cache.

const configStrategy = {
  cache: {
    engine: "redis",
    host: "localhost",
    port: "6830",
    password: "dsdsdsd",
    enableTsl: "0",
    defaultTtl: 36000,
    consistentBehavior: "1"
  }
}

Memcache Example

Following is an example of memcache engine config strategy to be used in initializing Cache.

const configStrategy = {
  cache: {
    engine: "memcached",
    servers: ["127.0.0.1:11211"],
    defaultTtl: 36000,
    consistentBehavior: "1"
  }
}

In-memory Example

Following is an example of in-memory engine config strategy to be used in initializing Cache.

const configStrategy = {
  cache: {
    engine: "none",
    namespace: "A",
    defaultTtl: "36000",
    consistentBehavior: "1"
  }
}

cacheImplementer methods

Irrespective of the caching engine, the methods exposed in cacheImplementer have the consistent signature.

Store and retrieve data in cache using set and get:

const resolvePromise = function(cacheResponse){
                           if (cacheResponse.isSuccess()) {
                             console.log(cacheResponse.data.response);
                           } else {
                             console.log(cacheResponse);
                           }
                         };

cacheImplementer.set('testKey', 'testValue', 5000).then(resolvePromise);

cacheImplementer.get('testKey').then(resolvePromise);

Manage objects in cache using setObject and getObject:

cacheImplementer.setObject('testObjKey', {dataK1: 'a', dataK2: 'b'}).then(resolvePromise);
cacheImplementer.getObject('testObjKey').then(resolvePromise);

Retrieve multiple cache data using multiGet:

NOTE: Redis returns null from multiGet for objects, even if a value is set in the cache. The other caching implementers match this behaviour.

cacheImplementer.set('testKeyOne', 'One').then(console.log);
cacheImplementer.set('testKeyTwo', 'Two').then(console.log);
cacheImplementer.multiGet(['testKeyOne', 'testKeyTwo']).then(resolvePromise);

Delete cache using del:

cacheImplementer.set('testKey', 'testValue').then(console.log);
cacheImplementer.del('testKey').then(resolvePromise);

Manage counters in cache using increment and decrement:

cacheImplementer.set('testCounterKey', 1).then(console.log);
cacheImplementer.increment('testCounterKey', 10).then(resolvePromise);
cacheImplementer.decrement('testCounterKey', 5).then(resolvePromise);

Change the cache expiry time using touch:

cacheImplementer.set('testKey', "testData").then(console.log);
cacheImplementer.touch('testKey', 10).then(resolvePromise);

Running test cases

Set environment variables of particular cache engine for which you want to run the tests.

  • Redis
source test/env/redis.sh
  • Memcached
source test/env/memcached.sh
  • In-memory
source test/env/inMemory.sh

Cache engines must be running on the specified ports.

  • Redis (6380,6381)
redis-server --port 6380
  • Memcached (11212,11213,11214,11215)
memcached -p 11212 -d

Run tests

./node_modules/.bin/mocha --recursive "./test/*.js"
You might also like...

BullMQ - Premium Message Queue for NodeJS based on Redis

BullMQ - Premium Message Queue for NodeJS based on Redis

The fastest, most reliable, Redis-based distributed queue for Node. Carefully written for rock solid stability and atomicity. Read the documentation F

Dec 30, 2022

Nodejs Background jobs using redis.

Nodejs Background jobs using redis.

node-resque: The best background jobs in node. Distributed delayed jobs in nodejs. Resque is a background job system backed by Redis (version 2.6.0 an

Jan 3, 2023

egg.js(jwt) + mysql(sequelize) + redis + docker + docker-compose + nginx + vue + element-ui 全栈获取省市区数据(统计局数据)【工具】项目,实现在docker环境中一键部署

Egg-spider Preview 线上预览地址 (https://ronaldoxzb.com/) admin admin Project description [后端]egg.js(jwt) + mysql(sequelize) + redis + docker + docker-compo

Sep 29, 2022

Serverless URL Shortener made with Next.js + Redis.

Serverless URL Shortener made with Next.js + Redis.

linki: a place for your links linki is a url shortener made with next.js and redis! built with simplicity in mind, it's all in one page. deploy your o

Sep 15, 2022

Full type-safe Redis PubSub with Zod

redis-pubsub Full type-safe Redis PubSub system with async iterators Features Type-safety with Zod Out-of-the-box support for Date/Map/Set/BigInt seri

Dec 21, 2022

🪦 Redis Key Value store backed by IPFS

🪦 Redis Key Value store backed by IPFS

🪦 RipDB 🪦 A snappy, decentralized JSON store perfect for fast moving web3 builders. Redis + IPFS = RIP = 😍 Install With a Package Manager (browser

Dec 13, 2022

A simple package for single or batch image download and conversion using node streams.

image-batch-download A simple package for basic image downloading and processing. Supported formats: JPEG PNG WebP Installation With Yarn: yarn add im

Jan 2, 2022

Premium Queue package for handling distributed jobs and messages in NodeJS.

Premium Queue package for handling distributed jobs and messages in NodeJS.

The fastest, most reliable, Redis-based queue for Node. Carefully written for rock solid stability and atomicity. Sponsors · Features · UIs · Install

Dec 31, 2022

Making service workers easy so that your app is fast and reliable, even offline.

tulo.js Making service workers easy to use so that your app can be fast and reliable, even offline. Welcome to tulo.js, a service worker library that

Nov 16, 2022
Releases(v1.0.0)
  • v1.0.0(Oct 18, 2022)

    UniCache v1.0.0

    • First release of UniCache having support for 3 caching engines - Memcached, Redis and In-memory Cache
    • Test case coverage improved to 95%.
    Source code(tar.gz)
    Source code(zip)
Owner
PLG Works
We design, build and deliver highly scalable and secure web and mobile applications using React, Next.js, React Native, Web3.js, Node.js, Ruby On Rails.
PLG Works
Serve read-only Redis data over a HTTP API with auth

Redis data exposer This was created for Cliptok and not intended for use outside of it. Use at your own peril. This application will serve an API that

Erisa A 10 May 28, 2022
A fast, robust and extensible distributed task/job queue for Node.js, powered by Redis.

Conveyor MQ A fast, robust and extensible distributed task/job queue for Node.js, powered by Redis. Introduction Conveyor MQ is a general purpose, dis

Conveyor MQ 45 Dec 15, 2022
A simple Node.js APIBAN client for downloading banned IPs and inserting them into a redis set

apiban-redis A simple Node.js APIBAN client for downloading banned IPs and inserting them into a redis set. Installation This utility can be run as a

jambonz 4 Apr 5, 2022
Kue is a priority job queue backed by redis, built for node.js.

Kue Kue is no longer maintained Please see e.g. Bull as an alternative. Thank you! Kue is a priority job queue backed by redis, built for node.js. PRO

Automattic 9.4k Dec 20, 2022
A simple, fast, robust job/task queue for Node.js, backed by Redis.

A simple, fast, robust job/task queue for Node.js, backed by Redis. Simple: ~1000 LOC, and minimal dependencies. Fast: maximizes throughput by minimiz

Bee Queue 3.1k Jan 5, 2023
A simple high-performance Redis message queue for Node.js.

RedisSMQ - Yet another simple Redis message queue A simple high-performance Redis message queue for Node.js. For more details about RedisSMQ design se

null 501 Dec 30, 2022
SSHOT is a ✨ Web Screenshot API ✨ with caching kept in mind!

label icon Quick Start rocket Welcome to SSHOT (/s:shot/) SSHOT is a ✨ Web Screenshot API ✨ with caching kept in mind! Just pass in the parameters for

Amresh Prasad Sinha 9 Dec 24, 2022
Redis-backed task queue engine with advanced task control and eventual consistency

idoit Redis-backed task queue engine with advanced task control and eventual consistency. Task grouping, chaining, iterators for huge ranges. Postpone

Nodeca 65 Dec 15, 2022
An open-source link shortener built with Vercel Edge Functions and Upstash Redis.

Dub An open-source link shortener built with Vercel Edge Functions and Upstash Redis. Introduction · Deploy Your Own · Contributing Introduction Dub i

Steven Tey 4.9k Jan 5, 2023
Redis Simple Message Queue

Redis Simple Message Queue A lightweight message queue for Node.js that requires no dedicated queue server. Just a Redis server. tl;dr: If you run a R

Patrick Liess 1.6k Dec 27, 2022