Advertisement
Guest User

Untitled

a guest
Jun 9th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import _ from 'lodash';
  2. import Redis from 'ioredis';
  3. import config from './environment';
  4. import logger from './logger';
  5.  
  6. Redis.Command.setReplyTransformer('zrevrangebyscore', result => {
  7.   const data = [];
  8.   for (let i = 0; i < result.length; i += 2) {
  9.     const object = {
  10.       username: result[i],
  11.       points: parseInt(result[i + 1], 10)
  12.     };
  13.     data.push(object);
  14.   }
  15.   return data;
  16. });
  17.  
  18. Redis.Command.setReplyTransformer('zscore', result => parseInt(result, 10));
  19.  
  20. Redis.Command.setReplyTransformer('zrem', result => result === 1);
  21.  
  22. Redis.Command.setReplyTransformer('exists', result => result === 1);
  23.  
  24. Redis.Command.setReplyTransformer('sadd', result => result === 1);
  25.  
  26. Redis.Command.setReplyTransformer('srem', result => result === 1);
  27.  
  28. Redis.Command.setReplyTransformer('sismember', result => result === 1);
  29.  
  30. Redis.Command.setReplyTransformer('zincrby', result => parseInt(result, 10));
  31.  
  32. /**
  33.  * General stuff + subscribe connection
  34.  * use redis.pipeline if > 5 commands
  35.  */
  36. const redis = new Redis({
  37.   port: config.redis.port,
  38.   host: config.redis.host,
  39.   password: config.redis.password,
  40.   db: config.redis.db,
  41.   retryStrategy(times) {
  42.     const delay = Math.min(times * 50, 2000);
  43.     return delay;
  44.   },
  45.   reconnectOnError(err) {
  46.     const targetError = 'READONLY';
  47.     if (err.message.slice(0, targetError.length) === targetError) {
  48.       return true;
  49.     }
  50.   }
  51. });
  52.  
  53. /**
  54.  * Redis connection for publishing
  55.  */
  56. export const pub = new Redis({
  57.   port: config.redis.port,
  58.   host: config.redis.host,
  59.   password: config.redis.password,
  60.   db: config.redis.db
  61. });
  62.  
  63. /**
  64.  * Redis connection for publishing
  65.  */
  66. export const sub = new Redis({
  67.   port: config.redis.port,
  68.   host: config.redis.host,
  69.   password: config.redis.password,
  70.   db: config.redis.db
  71. });
  72.  
  73. export default redis;
  74.  
  75. redis.on('connect', () => {
  76.   logger.info('Established a connection to redis');
  77. });
  78.  
  79. redis.on('reconnecting', time => {
  80.   logger.info('Reconnecting..', time);
  81. });
  82.  
  83. redis.on('error', error => {
  84.   logger.error('Failed to connect to redis', error);
  85. });
  86.  
  87. redis.on('close', () => {
  88.   logger.info('Redis server connection has closed.');
  89. });
  90.  
  91. redis.on('end', () => {
  92.   logger.info('Failed to reconnect to redis');
  93. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement