redis.js 1.5 KB
Newer Older
mntmn's avatar
mntmn committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';

const RedisConnection = require('ioredis');
const websockets = require('./websockets');

module.exports = {
  connectRedis(){
    const redisHost = process.env.REDIS_PORT_6379_TCP_ADDR || 'localhost';
    this.connection = new RedisConnection(6379, redisHost);
  },
  sendMessage(action, model, attributes, channelId) {
    const data = JSON.stringify({
      channel_id: channelId,
      action: action,
      model: model,
      object: attributes
    });
    this.connection.publish('updates', data);
  },
  logIp(ip, cb) {
    this.connection.incr("ip_"+ ip, (err, socketCounter) => {
      cb();
    });
  },
  rateLimit(namespace, ip, cb) {
    const key = "limit_"+ namespace + "_"+ ip;
    const redis = this.connection;

    redis.get(key, (err, count)=> {
      if (count) {
        if(count < 150) {
          redis.incr(key, (err, newCount) => {
            if (newCount==150) {
              // limit
            }
            cb(true);
          });
        } else {
          cb(false);
        }
      } else {
        redis.set(key, 1, (err, count) => {
          redis.expire(key, 1800, (err, expResult) => {
            cb(true);
          });
        });
      }
    });
  }, 
  isOnlineInSpace(user, space, cb) {
    this.connection.smembers("space_" + space._id.toString(), function(err, list) {
      if (err) cb(err);
      else {
        var users = list.filter(function(item) {
          return user._id.toString() === item;
        });
        cb(null, (users.length > 0));
      }
    });
  }
};