perspective/perspective

View on GitHub
lib/server/events-repo.js

Summary

Maintainability
A
1 hr
Test Coverage
var logger = require('./logger');
var co = require('co');
var debug = logger.debug.bind(null, 'db:events');
var info = logger.info.bind(null, 'db:events');
var error = logger.error.bind(null, 'db:events');

var Repo = function(db) {
  this.db = db;
};

Repo.prototype = {

  _prepare: function () {
    return co(function* () {
      debug('_prepare');
      var tableList = yield this.db.tableList();

      if(tableList.indexOf('events') === -1) {
        info('_prepare', 'creating...');
        yield this.db.tableCreate('events');
        yield this.db.table('events').indexCreate('time');
        yield this.db.table('events').indexCreate('type');
      }
    }.bind(this));
  },

  getEvents: function *(){
    debug('getEvents');
    return yield this.db.table('events').orderBy({ index: 'time' });
  },

  getUsers: function *(){
    debug('getUsers');
    return yield this.db.table('events').filter({ type: 'user' });
  },

  changes: function () {
    return this.db.table('events').changes().run();
  },
  insert: function(event) {
    debug('insert', event);
    event.time = new Date();

    return co(function* (val) {
      var result = yield this.db.table('events').insert(event, {returnChanges: true});

      if(result.inserted === 1) {
        return yield Promise.resolve(result.changes[0].new_val);
      } else {
        logger.error('db:insert:fail', result);
        return yield Promise.reject();
      }
    }.bind(this));
  }
};

module.exports = Repo;