Module for connecting to either single, sentinel or cluster redis. Comes with added power of building and running multi commands (pipeline and transaction).
yarn install @shivam-tripathi/redis-wrapper-ts
RedisStore requires the following values:
- service:
string- Identifier for this instance. Can be any string. - config:
RedisConfig- Config for connection. See the next section for details. - emitter?:
events.EventEmitter- Event emitter for relevant events related data. The events arelog,successanderror. This is useful if one needs custom logging for the events. The data emitted would be of type:The emitter defaults to usinginterface Event { service: string; message: string; data?: any; error?: Error; }
console.logfor all events.
- Cluster
interface ClusterConfig {
cluster: {
hosts: { host: string; port: number }[];
};
password?: string;
}- Sentinel
interface SentinelConfig {
sentinel: {
name: string;
hosts: { host: string; port: number }[];
};
db?: number;
password?: string;
}- Single
interface SingleConfig {
host: string;
port: number;
db?: number;
password?: string;
}Preference of read is cluster > sentinel > single.
const Redis = require('@shivam/redis');
async function boot() {
const redis = Redis.RedisStore('RedisNameIdentifier', {
auth: { use: true, password: 'redisPassword' },
host: 'localhost',
port: '6379',
db: 3,
});
await redis.init();
await redis.client.set('one', 101);
console.log(await redis.client.get('one'));
}
boot();Multi interface is defined as:
interface PipelineAction {
cmd: string; // Redis command you wish to execute, eg 'get', 'hget', 'del', 'hmset' etc
args?: any[]; // Related args, for example with 'get' args would be ['keyName']
before?: (_?: any[]) => any[]; // Function you wish to run on args before calling the command
after?: (result: any) => any; // Function you wish to run on the result
}
interface MultiAction {
actions: { [id: string]: PipelineAction };
executed: boolean;
results: { [id: string]: any };
addAction: (id: string, action: PipelineAction) => void;
addCommand: (id: string, cmd: string, ...args: any[]) => void;
exec: () => Promise<any>;
}- Transaction
async function demo() {
const transaction = redis.transaction();
transaction.addAction('getOne', {
cmd: 'get',
args: ['one'],
});
transaction.addAction('hashMapSetTwo', {
cmd: 'hmset',
args: ['two', { foo: 'bar' }],
});
transaction.addCommand('getTwoFoo', 'hget', 'two', 'foo');
const { getOne, hashMapSetTwo, getTwoFoo } = await transaction.exec();
}Same code will be repeated for pipline, just replace redis.transaction with redis.pipeline.