Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import _ from 'lodash';
- import Redis from 'ioredis';
- import config from './environment';
- import logger from './logger';
- Redis.Command.setReplyTransformer('zrevrangebyscore', result => {
- const data = [];
- for (let i = 0; i < result.length; i += 2) {
- const object = {
- username: result[i],
- points: parseInt(result[i + 1], 10)
- };
- data.push(object);
- }
- return data;
- });
- Redis.Command.setReplyTransformer('zscore', result => parseInt(result, 10));
- Redis.Command.setReplyTransformer('zrem', result => result === 1);
- Redis.Command.setReplyTransformer('exists', result => result === 1);
- Redis.Command.setReplyTransformer('sadd', result => result === 1);
- Redis.Command.setReplyTransformer('srem', result => result === 1);
- Redis.Command.setReplyTransformer('sismember', result => result === 1);
- Redis.Command.setReplyTransformer('zincrby', result => parseInt(result, 10));
- /**
- * General stuff + subscribe connection
- * use redis.pipeline if > 5 commands
- */
- const redis = new Redis({
- port: config.redis.port,
- host: config.redis.host,
- password: config.redis.password,
- db: config.redis.db,
- retryStrategy(times) {
- const delay = Math.min(times * 50, 2000);
- return delay;
- },
- reconnectOnError(err) {
- const targetError = 'READONLY';
- if (err.message.slice(0, targetError.length) === targetError) {
- return true;
- }
- }
- });
- /**
- * Redis connection for publishing
- */
- export const pub = new Redis({
- port: config.redis.port,
- host: config.redis.host,
- password: config.redis.password,
- db: config.redis.db
- });
- /**
- * Redis connection for publishing
- */
- export const sub = new Redis({
- port: config.redis.port,
- host: config.redis.host,
- password: config.redis.password,
- db: config.redis.db
- });
- export default redis;
- redis.on('connect', () => {
- logger.info('Established a connection to redis');
- });
- redis.on('reconnecting', time => {
- logger.info('Reconnecting..', time);
- });
- redis.on('error', error => {
- logger.error('Failed to connect to redis', error);
- });
- redis.on('close', () => {
- logger.info('Redis server connection has closed.');
- });
- redis.on('end', () => {
- logger.info('Failed to reconnect to redis');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement