RethinkDB and Meteor


#1

I’m attempting to use RethinkDB with Meteor. Here’s what I have so far. It seems to work.

alertsCursors = {};

Meteor.publish('alerts', function(playerId) {
  var self = this;

  if(!self.userId) {
    return this.ready();
  }

  r.db('test')
    .table('alerts')
    .filter(r.row('playerIds').contains(function(player) {
        return player('playerId').eq(playerId);
    }))
    .changes({includeInitial:true, squash:true, includeTypes:true, includeOffsets:false, includeStates:false})
    .run(connection, function(err, cursor) {
      if (err) throw err;
      alertsCursors[self.userId] = cursor;
      
      cursor.each(function(err, row) {
        if (err) throw err;

        switch (row.type) {
          case 'initial':
          case 'add':
            self.added('alerts', row.new_val.id, _.omit(row.new_val, 'id'));
            break;

          case 'change':
            if (row.new_val.id != row.old_val.id) {
              // inserts are reported as changes??????
              self.added('alerts', row.new_val.id, _.omit(row.new_val, 'id'));
            } else {
              // get keys that changed by comparing new and old
              // should use _.omit but it's broken in this version of underscore
              // _.omit(old, function(v,k) {return new[k] === v;})
              let keys = _.keys(row.new_val);
              let newObj = EJSON.clone(row.new_val);
              for (var i = 0, length = keys.length; i < length; i++) {
                if (_.isEqual(row.old_val[keys[i]], newObj[keys[i]])) {
                  delete newObj[keys[i]];
                }
              }
              self.changed('alerts', row.new_val.id, newObj);
            }
            break;

          case 'remove':
            self.removed('alerts', row.old_val.id);
            break;
        }
      });
    });

  self.onStop(function() {
    if (alertsCursors[self.userId]) {
      alertsCursors[self.userId].close(function (err) {
        if (err) {
          console.log("An error occurred on cursor close");
        }
      });
      delete alertsCursors[self.userId];
    }
  });

  this.ready();
});

Hoping it will fix server cpu issues. If anyone spots problems or improvements please let me know.