<commit_before>var ChildProcess = require('child_process');
var http = require('http');
var Promise = require('bluebird');
var fs = require('fs');
Promise.promisifyAll(fs);
var quickTemp = require('quick-temp');
var expect = require('chai').expect;
var spy = require('sinon').spy;

var utils = require('../utils.js');
var openSpy = spy();
var host = require('proxyquire')('../../lib/commands/host.js', {'open': openSpy});

var directory = {};
var variationJS = '$(\'body\').addClass(\'test\'); $("body").append("<%-files.test %>");';
var experimentJS = 'function myFunc(){console.log("testing is fun");}';
var fileHTML = '
\n\tThis is a file test\n
';
var CSS = '.test {background: blue}';
var server, browser, oldDir;

describe('Host Command', function(){
  before(function(done){
    //Create temporary project directory
    quickTemp.makeOrRemake(directory, 'project');
    directory.experiment = directory.project + '/test-experiment/';
    directory.variation = directory.project + '/test-experiment/test-variation';

    //Initialize a project, create experiment, and create a variation
    utils.init(directory.project);
    utils.experiment(directory.experiment);
    utils.variation(directory.experiment, '/test-variation', 'Variation 1');

    fs.writeFileAsync(directory.variation + '/variation.js', variationJS)
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/experiment.css', CSS);
      })
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/experiment.js', experimentJS);
      })
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/test.html', fileHTML);
      })
      .then(function() {
        oldDir = process.cwd();
        process.chdir(directory.project);
        server = host(directory.variation, 9569 , {ssl: false, silence: true});
        done();
      })
      .catch(function(error){
        assert(false, 'Could not add css/javascript to files');
        done();
      });
  });
  after(function(done){
    process.chdir(oldDir);
    server.close();
    //Remove the temporary directory
    quickTemp.remove(directory, 'project');
    done();
  });
  it('Should host the landing page on the default port', function(done){
    http.get('http://localhost:9569/', function(res){
      expect(res.statusCode).to.equal(200);
      done();
    }).on('error', function(err) {
      console.log("Got error: " + err.message);
      done(err);
    })
  });

  // Store the contents of variation.js so they can be used in the next assertion.
  var resJS = '';
  it('Should host variation.js', function(done){
    request = http.get('http://localhost:9569/variation.js', function(res){
      expect(res.statusCode).to.equal(200);
    }).on('error', function(err){
      console.log('Got error:' + err.message);
      done();
    }).on('response', function(res) {
      res.on('readable', function() {
        resJS += res.read().toString('utf8');
      })
      res.on('end', function() {
        done();
      });
      res.on('error', function(err) {
        console.log('Got error:' + err.message);
        done();
      });
    });;
  });
  it('Should compile an external file using EJS', function(done) {
    expect(resJS).to.contain('
This is a file test
');
    done();
  });
  it('Should host variation.css', function(done){
    http.get('http://localhost:9569/variation.css', function(res){
      expect(res.statusCode).to.equal(200);
      done();
    }).on('error', function(err){
      console.log('Got error:' + err.message);
    });
  });
  describe('Open flag', function(){
    it('Should run the open command', function(done){
      expect(openSpy.called).to.be.true;
      done();
    });
  })

});<commit_msg>Fix some reversions created during the merge<commit_after>var ChildProcess = require('child_process');
var http = require('http');
var Promise = require('bluebird');
var fs = require('fs');
Promise.promisifyAll(fs);
var quickTemp = require('quick-temp');
var expect = require('chai').expect;
var spy = require('sinon').spy;

var utils = require('../utils.js');
var openSpy = spy();
var host = require('proxyquire')('../../lib/commands/host.js', {'open': openSpy});

var directory = {};
var variationJS = '$(\'body\').addClass(\'test\'); $("body").append("<%-files.test %>");';
var experimentJS = 'function myFunc(){console.log("testing is fun");}';
var fileHTML = '
\n\tThis is a file test\n
';
var CSS = '.test {background: blue}';
var server, browser, oldDir;

describe('Host Command', function(){
  before(function(done){
    //Create temporary project directory
    quickTemp.makeOrRemake(directory, 'project');
    directory.experiment = directory.project + '/test-experiment/';
    directory.variation = directory.project + '/test-experiment/test-variation';

    //Initialize a project, create experiment, and create a variation
    utils.init(directory.project);
    utils.experiment(directory.experiment);
    utils.variation(directory.experiment, '/test-variation', 'Variation 1');

    fs.writeFileAsync(directory.variation + '/variation.js', variationJS)
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/experiment.css', CSS);
      })
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/experiment.js', experimentJS);
      })
      .then(function(){
        return fs.writeFileAsync(directory.experiment + '/test.html', fileHTML);
      })
      .then(function() {
        // Don't host until all files are created, or test.html might be empty/non-existent
        oldDir = process.cwd();
        process.chdir(directory.project);
        server = host(directory.variation, 9569 , {ssl: false, silence: true, open: true});
        done();
      })
      .catch(function(error){
        expect(error).to.be.null;
        done();
      });
  });
  after(function(done){
    process.chdir(oldDir);
    server.close();
    //Remove the temporary directory
    quickTemp.remove(directory, 'project');
    done();
  });
  it('Should host the landing page on the default port', function(done){
    http.get('http://localhost:9569/', function(res){
      expect(res.statusCode).to.equal(200);
      done();
    }).on('error', function(err) {
      console.log("Got error: " + err.message);
      done(err);
    });
  });

  // Store the contents of variation.js so they can be used in the next assertion.
  var resJS = '';
  it('Should host variation.js', function(done){
    http.get('http://localhost:9569/variation.js', function(res){
      expect(res.statusCode).to.equal(200);
    }).on('error', function(err){
      console.log('Got error:' + err.message);
      done();
    }).on('response', function(res) {
      res.on('readable', function() {
        resJS += res.read().toString('utf8');
      })
      // Don't call done() until resJS is completely populated.
      res.on('end', function() {
        done();
      });
      res.on('error', function(err) {
        console.log('Got error:' + err.message);
        done();
      });
    });;
  });
  it('Should compile an external file using EJS', function(done) {
    expect(resJS).to.contain('
This is a file test
');
    done();
  });
  it('Should host variation.css', function(done){
    http.get('http://localhost:9569/variation.css', function(res){
      expect(res.statusCode).to.equal(200);
      done();
    }).on('error', function(err){
      console.log('Got error:' + err.message);
    });
  });
  describe('Open flag', function(){
    it('Should run the open command', function(done){
      expect(openSpy.called).to.be.true;
      done();
    });
  })

});<|endoftext|>


<commit_before>/* eslint-disable no-console */

const async = () => {
    return Promise.resolve();
};

const config = require('./config');

async()
    .then(() => require('./db').init(config.connectionString))
    .then((db) => require('./data').init(db))
    .then((data) => require('./app').init(data))
    .then((app) => {
        app.listen(config.port, () =>
            console.log(`Server works at :${config.port}`));
    })
    .catch((err) => {
        console.log(err);
    });
<commit_msg>Fixed paths<commit_after>/* eslint-disable no-console */

const async = () => {
    return Promise.resolve();
};

const config = require('./config');

async()
    .then(() => require('./db/db').init(config.connectionString))
    .then((db) => require('./data/data').init(db))
    .then((data) => require('./app/app').init(data))
    .then((app) => {
        app.listen(config.port, () =>
            console.log(`Server works at :${config.port}`));
    })
    .catch((err) => {
        console.log(err);
    });
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect;
const sinon  = require('sinon');

const CommandInjector = require('./command-mock-utils').CommandInjector;
const getGlobals      = require('./command-mock-utils').getGlobals;
const addItem         = require('./command-mock-utils').addItem;
const addNpc          = require('./command-mock-utils').addNpc;
const getCallCounter  = require('./command-mock-utils').getCallCounter;

const Time   = require('../../src/time').Time;
const Player = require('../../src/player').Player;
const Npc    = require('../../src/npcs').Npc;
const Room   = require('../../src/rooms').Room;
const Type   = require('../../src/type').Type;
const Item   = require('../../src/items').Item;
Type.config(Player, Npc, Item, {});

const socket = {
  write: sinon.stub()
}

const player = new Player(socket);

const lookCmd = require('../../commands/look').command;
const globals = getGlobals();
const look = CommandInjector(lookCmd, globals);

const [ rooms, items, players, npcs, Commands ] = globals;
players.addPlayer(player);

sinon.spy(player, 'say');
sinon.spy(player, 'write');
sinon.stub(Time, 'isDay');

const getPlayerSayCall = getCallCounter(player.say);

const location = 4;
const description = 'room desc';
const short_desc = 'room shortdesc';
const dark_desc = 'room darkdesc';
const area = 'The Dungeon';
const title = 'Treasure Chamber';
const room = new Room({ area, title, location, short_desc, dark_desc, description });

rooms.addRoom(room);
player.setLocation(location);
player.setPreference('roomdescs', 'default');

const shield = addItem({
  items, room, location,
  short_description: 'a shield',
  room_description: 'a sturdy shield',
  keywords: ['shield'],
  uuid: 'shield'
});

const goblin = addNpc({
  room, location, npcs,
  attributes: { level: 1 },
  short_description: 'a goblin',
  room_description: 'a menacing goblin',
  keywords: ['goblin'],
  uuid: 'gobbo'
});

describe('Look command', () => {

  describe('Looking at a room', () => {

    describe('looking at the room during the day', () => {
      Time.isDay.returns(true);

      look('', player);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show long description since player has not explored the room yet and their preference is default', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === description).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<green>a menacing goblin</green>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('looking at a room while it is dark', () => {
      Time.isDay.returns(false);

      look('', player);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show dark description', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === dark_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<green>a menacing goblin</green>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('looking at a room with after having explored it', () => {
      Time.isDay.returns(true);
      goblin.setAttribute('level', -4);

      const hasExplored = true;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show short description by default after exploring', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === short_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (very easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<cyan>a menacing goblin</cyan>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('Looking at a room you have not explored with shortdesc preference', () => {

      Time.isDay.returns(true);
      player.setPreference('roomdescs', 'short');
      goblin.setAttribute('level', 30);

      const hasExplored = false;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show short description due to preferences', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === short_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (hard)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<red>a menacing goblin</red>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('Looking at a room you have explored with verbose desc preference', () => {

      Time.isDay.returns(true);
      player.setPreference('roomdescs', 'verbose');
      goblin.setAttribute('level', 2);
      const oldHasMet = player.hasMet;
      player.hasMet = () => true;
      goblin.name = 'Boblin';

      const hasExplored = true;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show verbose description due to preferences', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === description).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs by name if they have been met, color coded by threat level (medium)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<yellow>Boblin</yellow>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

      player.hasMet = oldHasMet;
    });

    Time.isDay.restore();
  });

  describe('Looking at an npc in a room', () => {
    look('goblin', player);

    it('should show goblin description', () => {
      const npcDescCall = getPlayerSayCall();
      expect(npcDescCall.args[0] === goblin.getDescription()).to.be.true;
    });

  });

  describe('Looking at an item in a room', () => {

  });

  describe('Looking at another player', () => {

  });

  describe('Looking at oneself', () => {

  });

  describe('Looking at adjacent rooms', () => {

  });

});
<commit_msg>Add test for looking at item in room.<commit_after>'use strict';

const expect = require('chai').expect;
const sinon  = require('sinon');

const CommandInjector = require('./command-mock-utils').CommandInjector;
const getGlobals      = require('./command-mock-utils').getGlobals;
const addItem         = require('./command-mock-utils').addItem;
const addNpc          = require('./command-mock-utils').addNpc;
const getCallCounter  = require('./command-mock-utils').getCallCounter;

const Time   = require('../../src/time').Time;
const Player = require('../../src/player').Player;
const Npc    = require('../../src/npcs').Npc;
const Room   = require('../../src/rooms').Room;
const Type   = require('../../src/type').Type;
const Item   = require('../../src/items').Item;
Type.config(Player, Npc, Item, {});

const socket = {
  write: sinon.stub()
}

const player = new Player(socket);

const lookCmd = require('../../commands/look').command;
const globals = getGlobals();
const look = CommandInjector(lookCmd, globals);

const [ rooms, items, players, npcs, Commands ] = globals;
players.addPlayer(player);

sinon.spy(player, 'say');
sinon.spy(player, 'write');
sinon.stub(Time, 'isDay');

const getPlayerSayCall = getCallCounter(player.say);

const location = 4;
const description = 'room desc';
const short_desc = 'room shortdesc';
const dark_desc = 'room darkdesc';
const area = 'The Dungeon';
const title = 'Treasure Chamber';
const room = new Room({ area, title, location, short_desc, dark_desc, description });

rooms.addRoom(room);
player.setLocation(location);
player.setPreference('roomdescs', 'default');

const shield = addItem({
  items, room, location,
  short_description: 'a shield',
  room_description: 'a sturdy shield',
  keywords: ['shield'],
  uuid: 'shield'
});

const goblin = addNpc({
  room, location, npcs,
  attributes: { level: 1 },
  short_description: 'a goblin',
  room_description: 'a menacing goblin',
  keywords: ['goblin'],
  uuid: 'gobbo'
});

describe('Look command', () => {

  describe('Looking at a room', () => {

    describe('looking at the room during the day', () => {
      Time.isDay.returns(true);

      look('', player);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show long description since player has not explored the room yet and their preference is default', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === description).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<green>a menacing goblin</green>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('looking at a room while it is dark', () => {
      Time.isDay.returns(false);

      look('', player);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show dark description', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === dark_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<green>a menacing goblin</green>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('looking at a room with after having explored it', () => {
      Time.isDay.returns(true);
      goblin.setAttribute('level', -4);

      const hasExplored = true;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show short description by default after exploring', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === short_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (very easy)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<cyan>a menacing goblin</cyan>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('Looking at a room you have not explored with shortdesc preference', () => {

      Time.isDay.returns(true);
      player.setPreference('roomdescs', 'short');
      goblin.setAttribute('level', 30);

      const hasExplored = false;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show short description due to preferences', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === short_desc).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs, color coded by threat level (hard)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<red>a menacing goblin</red>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

    });

    describe('Looking at a room you have explored with verbose desc preference', () => {

      Time.isDay.returns(true);
      player.setPreference('roomdescs', 'verbose');
      goblin.setAttribute('level', 2);
      const oldHasMet = player.hasMet;
      player.hasMet = () => true;
      goblin.name = 'Boblin';

      const hasExplored = true;
      look('', player, hasExplored);

      // check for all player.say calls...
      it('should give the area and room title', () => {
        const titleCall = getPlayerSayCall();
        const expectedTitle = area + ': ' + title;
        expect(titleCall.args[0] === expectedTitle).to.be.true;
      });

      it('should show verbose description due to preferences', () => {
        const descCall = getPlayerSayCall();
        expect(descCall.args[0] === description).to.be.true;
      });

      it('should do a newline after the room desc', () => {
        const newLineCall = getPlayerSayCall();
        expect(newLineCall.args[0] === '').to.be.true;
      });

      it('should show the item on the ground', () => {
        const itemCall = getPlayerSayCall();
        const expectedItemRoomDesc = '<magenta>a sturdy shield</magenta>';
        expect(itemCall.args[0] === expectedItemRoomDesc).to.be.true;
      });

      it('should show any NPCs by name if they have been met, color coded by threat level (medium)', () => {
        const npcCall = getPlayerSayCall();
        const expectedNpcRoomDesc = '<yellow>Boblin</yellow>';
        expect(npcCall.args[0] === expectedNpcRoomDesc).to.be.true;
      });

      it('should show a label for any of the room\'s exits', () => {
        const exitsCall = player.write.getCall(1);
        const expectedItemsLabel = '<yellow><bold>Obvious exits: </yellow></bold>';
        expect(exitsCall.args[0] === expectedItemsLabel).to.be.true;
      });

      it('should close the exits list with a bracket', () => {
        const exitCloseCall = getPlayerSayCall();
        expect(exitCloseCall.args[0] === ']').to.be.true;
      });

      player.hasMet = oldHasMet;
    });

    Time.isDay.restore();
  });

  describe('Looking at an npc in a room', () => {
    look('goblin', player);

    it('should show goblin description', () => {
      const npcDescCall = getPlayerSayCall();
      expect(npcDescCall.args[0] === goblin.getDescription()).to.be.true;
    });

  });

  describe('Looking at an item in a room', () => {
    look('shield', player);

    it('should show shield description', () => {
      const itemDescCall = getPlayerSayCall();
      expect(itemDescCall.args[0] === shield.getDescription()).to.be.true;

    });
  });

  describe('Looking at a container', () => {
    describe('Looking at an empty container', () => {

    });
    describe('Looking at a container with a thing in it', () => {

    });
  });

  describe('Looking at another player', () => {

  });

  describe('Looking at oneself', () => {

  });

  describe('Looking at adjacent rooms', () => {

  });

});
<|endoftext|>


<commit_before>var app = require('http').createServer(),
    io = require('socket.io').listen(app),
    spawn = require('child_process').spawn,
    fs = require('fs'),
    s3 = require('./s3');

var generateUserid = function() {
    var id = (Math.random().toString(36)+'00000000000000000').slice(2, 8);
    if (connectedUsers[id] === undefined) return id;
    else return generateUserid();
};

var connectedUsers = {};

var coders = io.of('/ruby').on('connection', function(socket) {

    var ruby,
        userid,
        socketOn = false;

    socket.on('codeBuild', function(data) {
        console.log(data);

        var fileSaveError,
            codeLoadError;

        // Save file
        s3.uploadFile(userid + '.rb', data.fileContent, function(error) {
            fileSaveError = error;

            // Emit file saved
            socket.emit('buildStatus', {
                output: error || 'Code saved.'
            });

            // Check file syntax?

            // Kill old IRB
            if (ruby) {
              oldRuby = ruby;
              oldRuby.kill();
            }

            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(data.fileContent + '\n', function(error) {
                codeLoadError = error;

                // Emit code loaded
                socket.emit('buildStatus', {
                    output: error || 'Game loaded.'
                });

                if (!fileSaveError && !codeLoadError) {
                    socket.emit('buildStatus', {
                        output: 'Build successful!'
                    });
                } else {
                    socket.emit('terminalError', {
                        output: 'Build failed!'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log(ruby.pid + ' STDOUT: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data.replace(/^(\b|\s)\w+\(\)(\s\n|\n)/, '')
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log(ruby.pid + ' STDERR: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
            });

            ruby.on('exit', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
                if (code === 0) {
                    socket.emit('terminalError', {
                        output: 'Ruby process exited.'
                    });
                }
            });

        });
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        try {
            ruby.stdin.write(data.input + '\n');
        } catch (e) {
            socket.emit('terminalError', {
                output: 'Couldn\'t talk to ruby. Did you Build your game?'
            });
        }
    });

    socket.on('reportUserid', function(data) {
        var oldSocket = connectedUsers[data.userid];
        var newOrAuthenticatedUser = !oldSocket || oldSocket === data.authid;

        if (data.userid && newOrAuthenticatedUser) {
            userid = data.userid;
        } else userid = generateUserid();

        console.log('User ' + userid + ' connected on ' + socket.id);

        // Store socket id because XHR polling causes race conditions
        connectedUsers[userid] = socket.id;
        socket.emit('confirmUserid', {
            userid: userid,
            authid: socket.id
        });

        s3.getFile(userid + '.rb', function(error, contents) {
            if (error) {
                fs.readFile('games/game.rb', function(error, contents) {
                    socket.emit('ready', {
                        output: 'Ready!',
                        fileContent: contents.toString()
                    });
                });
            } else {
                socket.emit('ready', {
                    output: 'Ready! Welcome back.',
                    fileContent: contents.toString()
                });
            }
        });
    });

    socket.on('disconnect', function() {
        console.log('User ' + userid + ' disconnected from ' + socket.id);
        // Only set to false if user doesn't already have a new socket
        if (socket.id == connectedUsers[userid]) {
            connectedUsers[userid] = false;
            console.log('User ' + userid + ' disconnected completely');
        }
    });

});

var players = io.of('/share').on('connection', function(socket) {
    var ruby,
        socketOn = false;

    socket.emit('buildStatus', {
        output: 'Loading game...'
    });

    fs.readFile('games/example-game.rb', function(error, contents) {
        if (error) {
            socket.emit('terminalError', {
                output: 'Error loading game. Try again later.'
            });
        } else {
            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(contents + '\n', function(error) {
                if (error) {
                    socket.emit('terminalError', {
                        output: 'Error loading game. Try again later.'
                    });
                } else {
                    // Emit code loaded
                    socket.emit('buildStatus', {
                        output: 'Game loaded. Type start() to play.'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log(ruby.pid + ' STDOUT: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data.replace(/^(\b|\s)\w+\(\)(\s\n|\n)/, '')
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log(ruby.pid + ' STDERR: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
            });

            ruby.on('exit', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
                if (code === 0) {
                    socket.emit('terminalError', {
                        output: 'Ruby process exited.'
                    });
                }
            });
        }
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        try {
            ruby.stdin.write(data.input + '\n');
        } catch (e) {
            socket.emit('terminalError', {
                output: 'Couldn\'t talk to ruby. Did you Build your game?'
            });
        }
    });

    socket.on('resetUsersForLab', function() {
        players.emit('clearUserid');
    });

    socket.on('clearUseridDone', function(data) {
        if (data !== '') console.log(data + ' not clear!');
    });
});

app.listen(process.env.PORT || 8888);
<commit_msg>Update message for players on irb error<commit_after>var app = require('http').createServer(),
    io = require('socket.io').listen(app),
    spawn = require('child_process').spawn,
    fs = require('fs'),
    s3 = require('./s3');

var generateUserid = function() {
    var id = (Math.random().toString(36)+'00000000000000000').slice(2, 8);
    if (connectedUsers[id] === undefined) return id;
    else return generateUserid();
};

var connectedUsers = {};

var coders = io.of('/ruby').on('connection', function(socket) {

    var ruby,
        userid,
        socketOn = false;

    socket.on('codeBuild', function(data) {
        console.log(data);

        var fileSaveError,
            codeLoadError;

        // Save file
        s3.uploadFile(userid + '.rb', data.fileContent, function(error) {
            fileSaveError = error;

            // Emit file saved
            socket.emit('buildStatus', {
                output: error || 'Code saved.'
            });

            // Check file syntax?

            // Kill old IRB
            if (ruby) {
              oldRuby = ruby;
              oldRuby.kill();
            }

            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(data.fileContent + '\n', function(error) {
                codeLoadError = error;

                // Emit code loaded
                socket.emit('buildStatus', {
                    output: error || 'Game loaded.'
                });

                if (!fileSaveError && !codeLoadError) {
                    socket.emit('buildStatus', {
                        output: 'Build successful!'
                    });
                } else {
                    socket.emit('terminalError', {
                        output: 'Build failed!'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log(ruby.pid + ' STDOUT: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data.replace(/^(\b|\s)\w+\(\)(\s\n|\n)/, '')
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log(ruby.pid + ' STDERR: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
            });

            ruby.on('exit', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
                if (code === 0) {
                    socket.emit('terminalError', {
                        output: 'Ruby process exited.'
                    });
                }
            });

        });
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        try {
            ruby.stdin.write(data.input + '\n');
        } catch (e) {
            socket.emit('terminalError', {
                output: 'Couldn\'t talk to ruby. Did you Build your game?'
            });
        }
    });

    socket.on('reportUserid', function(data) {
        var oldSocket = connectedUsers[data.userid];
        var newOrAuthenticatedUser = !oldSocket || oldSocket === data.authid;

        if (data.userid && newOrAuthenticatedUser) {
            userid = data.userid;
        } else userid = generateUserid();

        console.log('User ' + userid + ' connected on ' + socket.id);

        // Store socket id because XHR polling causes race conditions
        connectedUsers[userid] = socket.id;
        socket.emit('confirmUserid', {
            userid: userid,
            authid: socket.id
        });

        s3.getFile(userid + '.rb', function(error, contents) {
            if (error) {
                fs.readFile('games/game.rb', function(error, contents) {
                    socket.emit('ready', {
                        output: 'Ready!',
                        fileContent: contents.toString()
                    });
                });
            } else {
                socket.emit('ready', {
                    output: 'Ready! Welcome back.',
                    fileContent: contents.toString()
                });
            }
        });
    });

    socket.on('disconnect', function() {
        console.log('User ' + userid + ' disconnected from ' + socket.id);
        // Only set to false if user doesn't already have a new socket
        if (socket.id == connectedUsers[userid]) {
            connectedUsers[userid] = false;
            console.log('User ' + userid + ' disconnected completely');
        }
    });

});

var players = io.of('/share').on('connection', function(socket) {
    var ruby,
        socketOn = false;

    socket.emit('buildStatus', {
        output: 'Loading game...'
    });

    fs.readFile('games/example-game.rb', function(error, contents) {
        if (error) {
            socket.emit('terminalError', {
                output: 'Error loading game. Try again later.'
            });
        } else {
            // Start IRB
            ruby = spawn('irb');

            ruby.stdout.setEncoding('utf8');
            ruby.stderr.setEncoding('utf8');

            // Funnel file into IRB
            socketOn = false;
            ruby.stdin.write(contents + '\n', function(error) {
                if (error) {
                    socket.emit('terminalError', {
                        output: 'Error loading game. Try again later.'
                    });
                } else {
                    // Emit code loaded
                    socket.emit('buildStatus', {
                        output: 'Game loaded. Type start() to play.'
                    });
                }
            });

            // Bind events on IRB
            ruby.stdout.on('data', function(data) {
                console.log(ruby.pid + ' STDOUT: ' + data);
                if (socketOn) {
                    console.log('socket on');
                    socket.emit('terminalOutput', {
                        output: data.replace(/^(\b|\s)\w+\(\)(\s\n|\n)/, '')
                    });
                }
            });

            ruby.stderr.on('data', function(data) {
                console.log(ruby.pid + ' STDERR: ' + data);
                socket.emit('terminalError', {
                    output: data
                });
            });

            ruby.on('close', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
            });

            ruby.on('exit', function(code) {
                console.log(ruby.pid + ' Exit code: ' + code);
                if (code === 0) {
                    socket.emit('terminalError', {
                        output: 'Ruby process exited.'
                    });
                }
            });
        }
    });

    socket.on('terminalInput', function(data) {
        console.log(data);
        socketOn = true;
        try {
            ruby.stdin.write(data.input + '\n');
        } catch (e) {
            socket.emit('terminalError', {
                output: 'Couldn\'t talk to ruby. Try refreshing the browser.'
            });
        }
    });

    socket.on('resetUsersForLab', function() {
        players.emit('clearUserid');
    });

    socket.on('clearUseridDone', function(data) {
        if (data !== '') console.log(data + ' not clear!');
    });
});

app.listen(process.env.PORT || 8888);
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var express = require('express');

var server = module.exports = express();
var web = module.exports = express();
var api = module.exports = express();
var track = module.exports = express();
var redirect = module.exports = express();

// Config
var config = {
    domain: 'wrapulous.com',
    name: 'wrapulous',
    publicPath: '/public',
    viewPath: '/views',
    rootDir: __dirname,
};

// Mongoose
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/wrapulous');

// Setup
server.set('port', process.env.PORT || 5000);
server.set('views', config.rootDir + config.viewPath);
server.set('view engine', 'jade');
server.use(express.compress());
server.use(express.favicon(config.rootDir + config.publicPath + '/favicon.ico'));
server.use(express.logger('dev'));
server.use(express.bodyParser());
server.use(express.methodOverride());
server.use(require('stylus').middleware(config.rootDir + config.publicPath));
server.use(express['static'](config.rootDir + config.publicPath));

if ('development' == server.get('env')) {
    server.use(express.errorHandler());
}

// Controllers
var linkController = require('./controllers/v0/link.js');
var eventController = require('./controllers/v0/event.js');
var trackController = require('./controllers/track.js');

// App routes
web.get('/', function (req, res) {
    res.render('index');
});

web.get('/docs', function (req, res) {
    res.render('docs');
});

// API routes
api.get('/api/v0/links', linkController.list);
api.get('/api/v0/links/:linkId', linkController.details);
api.post('/api/v0/links', linkController.create);
api.get('/api/v0/link/:linkId/events', eventController.list);
api.get('/api/v0/link/:linkId/events/:eventId', eventController.details);

// Track routes
track.get('*', trackController.handle);

// Unkown subdomain redirect
redirect.all('*', function(req, res){
  res.redirect(config.domain + server.get('port') + req.subdomains[0]);
});

// Subdomain -> express app map
server.use(express.vhost('*.' + config.domain, redirect));
server.use(express.vhost('track.' + config.domain, track));
server.use(express.vhost('api.' + config.domain, api));
server.use(express.vhost(config.domain, web));

// Run
server.listen(server.get('port'));
console.log('Started ' + config.name + ' on port ' + server.get('port'));
console.log('Config used: ', config);
<commit_msg>fix redirect issue<commit_after>var mongoose = require('mongoose');
var express = require('express');

var server = module.exports = express();
var web = module.exports = express();
var api = module.exports = express();
var track = module.exports = express();
var redirect = module.exports = express();

// Config
var config = {
    domain: 'http://wrapulous.com',
    name: 'wrapulous',
    publicPath: '/public',
    viewPath: '/views',
    rootDir: __dirname,
};

// Mongoose
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/wrapulous');

// Setup
server.set('port', process.env.PORT || 5000);
server.set('views', config.rootDir + config.viewPath);
server.set('view engine', 'jade');
server.use(express.compress());
server.use(express.favicon(config.rootDir + config.publicPath + '/favicon.ico'));
server.use(express.logger('dev'));
server.use(express.bodyParser());
server.use(express.methodOverride());
server.use(require('stylus').middleware(config.rootDir + config.publicPath));
server.use(express['static'](config.rootDir + config.publicPath));

if ('development' == server.get('env')) {
    server.use(express.errorHandler());
}

// Controllers
var linkController = require('./controllers/v0/link.js');
var eventController = require('./controllers/v0/event.js');
var trackController = require('./controllers/track.js');

// App routes
web.get('/', function (req, res) {
    res.render('index');
});

web.get('/docs', function (req, res) {
    res.render('docs');
});

// API routes
api.get('/api/v0/links', linkController.list);
api.get('/api/v0/links/:linkId', linkController.details);
api.post('/api/v0/links', linkController.create);
api.get('/api/v0/link/:linkId/events', eventController.list);
api.get('/api/v0/link/:linkId/events/:eventId', eventController.details);

// Track routes
track.get('*', trackController.handle);

// Unkown subdomain redirect
redirect.all('*', function(req, res){
  res.redirect(config.domain + ':' + server.get('port') + req.subdomains[0]);
});

// Subdomain -> express app map
server.use(express.vhost('*.' + config.domain, redirect));
server.use(express.vhost('track.' + config.domain, track));
server.use(express.vhost('api.' + config.domain, api));
server.use(express.vhost(config.domain, web));

// Run
server.listen(server.get('port'));
console.log('Started ' + config.name + ' on port ' + server.get('port'));
console.log('Config used: ', config);
<|endoftext|>


<commit_before>'use strict';
// #1 define constants and requirements
const express = require('express');
const bodyParser = require('body-parser');
const pg = require('pg');
const tmi = require('tmi.js');
const app = express();
const PORT = process.env.PORT || 31337;

const conString = process.env.DATABASE_URL;
const client = new pg.Client(conString);
client.connect();
client.on('error', err => console.error(err));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('./public'));

// #2 set up the http requests
app.get('/', function(request, response){
	response.sendFile('public/index.html', {root: '.'});
});

app.listen(PORT, function() {
	console.log(`My server is running on port: ${PORT}`);
});

// #3 create Database
loadDB();

function loadDB() {
	client.query(`
		CREATE TABLE IF NOT EXISTS
		users (
			user_id SERIAL PRIMARY KEY,
			username VARCHAR(255) UNIQUE NOT NULL,
			widget_text VARCHAR(1000) NOT NULL,
			text_color VARCHAR(255) NOT NULL,
			fill_color VARCHAR(255) NOT NULL,
			goal INTEGER NOT NULL
		);`
	)
	.catch(console.error);

  client.query(`
    CREATE TABLE IF NOT EXISTS
    choices (
      choice_id SERIAL PRIMARY KEY,
      user_id INTEGER NOT NULL REFERENCES users(user_id),
      choice_text VARCHAR(255) NOT NULL,
			choice_color VARCHAR(255) NOT NULL,
			value INTEGER
    );`
  )
  .catch(console.error);
}

// #4 populate Database
app.post('/choices', (request, response) => {
	console.log(request);
	console.log(request.body);
  client.query(
    'INSERT INTO users(username, widget_text, text_color, fill_color, goal) VALUES($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING',
    [request.body.username, request.body.widgetText, request.body.textColor, request.body.fillColor, request.body.goal]
  )
  .then(() => {
    client.query(`
      INSERT INTO
      choices(user_id, choice_text, choice_color, value)
      SELECT author_id, $1, $2, $3
      FROM users
      WHERE username=$4;
      `,
      [
        request.body.choiceText,
        request.body.choiceColor,
        request.body.value,
        request.body.username,
      ]
    )
  })
  .then(() => response.send('Insert complete'))
  .catch(console.error);
});

app.delete('/choices/:username', (request, response) => {
  client.query(`
    DELETE FROM choices
    INNER JOIN users
			ON choices.user_id=users.user_id
		WHERE username = $1;`,
    [request.params.username]
  )
  .then(() => response.send('Delete complete'))
  .catch(console.error);
});

// #5 retrieve info from database
app.get('/choices/:username', (request, response) => {
  client.query(`
    SELECT * FROM choices
    INNER JOIN users
      ON choices.user_id=users.user_id
		WHERE username = $1;`,
		[request.params.username]
  )
  .then(result => {
		console.log(result.rows);
		response.send(result.rows);
	})
  .catch(console.error);
});
<commit_msg>Added body parser<commit_after>'use strict';
// #1 define constants and requirements
const express = require('express');
const bodyParser = require('body-parser');
const pg = require('pg');
const tmi = require('tmi.js');
const app = express();
const PORT = process.env.PORT || 31337;

const conString = process.env.DATABASE_URL;
const client = new pg.Client(conString);
client.connect();
client.on('error', err => console.error(err));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('./public'));

// #2 set up the http requests
app.get('/', function(request, response){
	response.sendFile('index.html', {root: '.'});
});

app.listen(PORT, function() {
	console.log(`My server is running on port: ${PORT}`);
});

// #3 create Database
loadDB();

function loadDB() {
	client.query(`
		CREATE TABLE IF NOT EXISTS
		users (
			user_id SERIAL PRIMARY KEY,
			username VARCHAR(255) UNIQUE NOT NULL,
			widget_text VARCHAR(1000) NOT NULL,
			text_color VARCHAR(255) NOT NULL,
			fill_color VARCHAR(255) NOT NULL,
			goal INTEGER NOT NULL
		);`
	)
	.catch(console.error);

  client.query(`
    CREATE TABLE IF NOT EXISTS
    choices (
      choice_id SERIAL PRIMARY KEY,
      user_id INTEGER NOT NULL REFERENCES users(user_id),
      choice_text VARCHAR(255) NOT NULL,
			choice_color VARCHAR(255) NOT NULL,
			value INTEGER
    );`
  )
  .catch(console.error);
}

// #4 populate Database
app.post('/choices', (request, response) => {
	console.log(request);
	console.log(request.body);
  client.query(
    'INSERT INTO users(username, widget_text, text_color, fill_color, goal) VALUES($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING',
    [request.body.username, request.body.widgetText, request.body.textColor, request.body.fillColor, request.body.goal]
  )
  .then(() => {
    client.query(`
      INSERT INTO
      choices(user_id, choice_text, choice_color, value)
      SELECT author_id, $1, $2, $3
      FROM users
      WHERE username=$4;
      `,
      [
        request.body.choiceText,
        request.body.choiceColor,
        request.body.value,
        request.body.username,
      ]
    )
  })
  .then(() => response.send('Insert complete'))
  .catch(console.error);
});

app.delete('/choices/:username', (request, response) => {
  client.query(`
    DELETE FROM choices
    INNER JOIN users
			ON choices.user_id=users.user_id
		WHERE username = $1;`,
    [request.params.username]
  )
  .then(() => response.send('Delete complete'))
  .catch(console.error);
});

// #5 retrieve info from database
app.get('/choices/:username', (request, response) => {
  client.query(`
    SELECT * FROM choices
    INNER JOIN users
      ON choices.user_id=users.user_id
		WHERE username = $1;`,
		[request.params.username]
  )
  .then(result => {
		console.log(result.rows);
		response.send(result.rows);
	})
  .catch(console.error);
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var mongoose = require('mongoose');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

mongoose.connect('mongodb://localhost/CoursePlanner');

app.use(express.static(_dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());

app.listen(8080);
console.log("App listening on port 8080");
<commit_msg>starting to implement node server<commit_after>var express = require('express');
var app = express();

var mongoose = require('mongoose');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

mongoose.connect('mongodb://localhost/CoursePlanner');

app.use(express.static(_dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());

var Plan = mongoose.model('Plan', {
//  json : String
});

app.get('/plans', function(req,res) {
  Plan.find(function(err,plans) {
    if(err) {
      res.send(err);
    }
    res.json(plans);
  });
});

app.listen(8080);
console.log("App listening on port 8080");
<|endoftext|>


<commit_before>var util = require('util');
var twitter = require('ntwitter');

process.on('uncaughtException', function(e) {
  console.debug(e);
});

var twit = new twitter({
  consumer_key: process.env.CONSUMER_KEY,
  consumer_secret: process.env.CONSUMER_SECRET,
  access_token_key: process.env.ACCESS_TOKEN,
  access_token_secret: process.env.ACCESS_TOKEN_SECRET
});

var fs = require('fs');
var app = require('http').createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(fs.readFileSync('index.html'));
}).listen(process.env.PORT || 5000);

var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
  socket.on('msg', function(data) {
    console.log('* connected ' + data);
    io.sockets.emit('msg', data);
  })
});

twit.stream('statuses/sample', function(stream) {
  stream.on('data', function (data) {
    if(data.lang === 'ja') {
      io.sockets.emit('msg', data);
      if(process.env.DRAIN_TWEETS === '1') {
        console.log(data);
      }
    }
  })
});

<commit_msg>debugging<commit_after>var util = require('util');
var twitter = require('ntwitter');

// process.on('uncaughtException', function(e) {
//   console.debug(e);
// });

var twit = new twitter({
  consumer_key: process.env.CONSUMER_KEY,
  consumer_secret: process.env.CONSUMER_SECRET,
  access_token_key: process.env.ACCESS_TOKEN,
  access_token_secret: process.env.ACCESS_TOKEN_SECRET
});

var fs = require('fs');
var app = require('http').createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(fs.readFileSync('index.html'));
}).listen(process.env.PORT || 5000);

var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
  socket.on('msg', function(data) {
    console.log('* connected ' + data);
    io.sockets.emit('msg', data);
  })
});

twit.stream('statuses/sample', function(stream) {
  stream.on('data', function (data) {
    if(data.lang === 'ja') {
      io.sockets.emit('msg', data);
      if(process.env.DRAIN_TWEETS === '1') {
        console.log(data);
      }
    }
  })
});

<|endoftext|>


<commit_before>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var Firebase = require("firebase")
var WebSocketServer = require('websocket').server;
var reqobj = require("request")

var fb = new Firebase("improvplusplus.firebaseIO.com");

var server = my_http.createServer(app).listen(3000,'0.0.0.0');

wsServer = new WebSocketServer({
    httpServer: server
});

var history = [];
var clients = [];
var num_msgs = 0;

app.use(bodyParser.json());

app.use('/', express.static('public'));

app.post('/login', function(req, res) {
    if(typeof req.body.username !== 'undefined' && typeof req.body.password !== 'undefined') {
        var info = {};
        info['username'] = req.body.username;
        info['password'] = req.body.password;
        info['loginStatus'] = 'OK';
        res.send(JSON.stringify(info));
    } else {
        var info = {};
        info['loginStatus'] = 'notFound';
        res.send(JSON.stringify(info));
    }
});

wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    var index = clients.push(connection) - 1;
    var username = false;
    var result = false;

    connection.on('message', function(message) {
        if(message.type === 'utf8') {
            var obj = message.utf8Data;
            var json_msg = JSON.parse(obj);
            username = json_msg.username;

	    //get number of messages
	    fb.child("num_msgs").on("value", function(snapshot) {
		num_msgs = snapshot.val();
	    },
	    function (errorObject) {
		fb.child("num_msgs").set(0);
	    });

	    var fb_messages = fb.child("messages");
	    fb_messages.child(num_msgs).set({
		obj
	    });

	    //log console because my dumbass computer doesn't do CSS
	    console.log(json_msg);

	    //record number of messages locally and on database
	    num_msgs++;
	    fb.child("num_msgs").set(num_msgs);
	    console.log(num_msgs);

            for(var i = 0; i < clients.length; i++) {
                clients[i].sendUTF(obj);
            }
        }
    });

    connection.on('close', function(reasonCode, description) {
        for(var i = 0; i < clients.length; i++) {
            clients[i].sendUTF(JSON.stringify({username: username, message: 'User disconnected.'}));
        }
    });
});
<commit_msg>what is your type<commit_after>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

var Firebase = require("firebase")
var WebSocketServer = require('websocket').server;
var reqobj = require("request")

var fb = new Firebase("improvplusplus.firebaseIO.com");

var server = my_http.createServer(app).listen(3000,'0.0.0.0');

wsServer = new WebSocketServer({
    httpServer: server
});

var history = [];
var clients = [];
var num_msgs = 0;

app.use(bodyParser.json());

app.use('/', express.static('public'));

app.post('/login', function(req, res) {
    if(typeof req.body.username !== 'undefined' && typeof req.body.password !== 'undefined') {
        var info = {};
        info['username'] = req.body.username;
        info['password'] = req.body.password;
        info['loginStatus'] = 'OK';
        res.send(JSON.stringify(info));
    } else {
        var info = {};
        info['loginStatus'] = 'notFound';
        info['typeOfUsername'] = typeof req.body.username;
        res.send(JSON.stringify(info));
    }
});

wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    var index = clients.push(connection) - 1;
    var username = false;
    var result = false;

    connection.on('message', function(message) {
        if(message.type === 'utf8') {
            var obj = message.utf8Data;
            var json_msg = JSON.parse(obj);
            username = json_msg.username;

	    //get number of messages
	    fb.child("num_msgs").on("value", function(snapshot) {
		num_msgs = snapshot.val();
	    },
	    function (errorObject) {
		fb.child("num_msgs").set(0);
	    });

	    var fb_messages = fb.child("messages");
	    fb_messages.child(num_msgs).set({
		obj
	    });

	    //log console because my dumbass computer doesn't do CSS
	    console.log(json_msg);

	    //record number of messages locally and on database
	    num_msgs++;
	    fb.child("num_msgs").set(num_msgs);
	    console.log(num_msgs);

            for(var i = 0; i < clients.length; i++) {
                clients[i].sendUTF(obj);
            }
        }
    });

    connection.on('close', function(reasonCode, description) {
        for(var i = 0; i < clients.length; i++) {
            clients[i].sendUTF(JSON.stringify({username: username, message: 'User disconnected.'}));
        }
    });
});
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2016/6/24.
 */

var http = require('http');
var FileSend = require('./index');
var colors = require('colors/safe');

var first = true;

http.createServer(function (request, response){
  var send = new FileSend(request, {
    maxAge: '3day',
    index: ['index.html']
  });

  if (first) {
    first = false;
    console.log('--------------------------------------------------------------------');
  }

  console.log('ROOT:', colors.red.bold(send.root));
  console.log('URL:', colors.green.bold(send.url));
  console.log('PATH:', colors.yellow.bold(send.path));
  console.log('REALPATH:', colors.cyan.bold(send.realpath));
  console.log('QUERY:', colors.green.bold(JSON.stringify(send.query, null, 2)));

  send.pipe(response).on('headers', function (){
    console.log('HEADERS:', colors.magenta.bold(JSON.stringify(send.headers, null, 2)));
    console.log('--------------------------------------------------------------------');
  });
}).listen(8080, '127.0.0.1');
<commit_msg>update files<commit_after>/**
 * Created by nuintun on 2016/6/24.
 */

var http = require('http');
var FileSend = require('./index');
var colors = require('colors/safe');

var first = true;

http.createServer(function (request, response){
  var send = new FileSend(request, {
    maxAge: '3day',
    ignore: ['((**)|/).*'],
    index: ['index.html']
  });

  if (first) {
    first = false;
    console.log('--------------------------------------------------------------------');
  }

  console.log('ROOT:', colors.red.bold(send.root));
  console.log('URL:', colors.green.bold(send.url));
  console.log('PATH:', colors.yellow.bold(send.path));
  console.log('REALPATH:', colors.cyan.bold(send.realpath));
  console.log('QUERY:', colors.green.bold(JSON.stringify(send.query, null, 2)));

  send.pipe(response).on('headers', function (){
    console.log('HEADERS:', colors.magenta.bold(JSON.stringify(send.headers, null, 2)));
    console.log('--------------------------------------------------------------------');
  });
}).listen(8080, '127.0.0.1');
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;

var util   = require('util');
var logger = require('./lib/logger');
var _      = require('lodash');
var net = require('net');
var Buckets = require('./lib/buckets');

var ResponseWriter = require('./lib/pipeline/response_writer');
var RequestHandler = require('./lib/pipeline/request_handler');
var RequestDecoder = require('./lib/pipeline/request_decoder');
var lps = require('length-prefixed-stream');
var lps_encode = require('./lib/lps_encode');
var validateConfig = require('./lib/config_validator');
var agent = require('auth0-instrumentation');

var db = require('./lib/db');
var enableDestroy = require('server-destroy');

var defaults = {
  port:      9231,
  hostname:  '0.0.0.0',
  log_level: 'info',
  protocol:  'protocol-buffers'
};

/*
 * Creates an instance of LimitdServer.
 *
 * Options:
 *
 *  - `db` the path to the database. Required.
 *  - `port` the port to listen to. Defaults to 9231.
 *  - `hostname` the hostname to bind to. Defaults to INADDR_ANY
 *  - `log_level` the verbosity of the logs. Defaults to 'info'.
 *  - `metrics_api_key`, the DataDog api key to log metrics to. Defaults to undefined.
 *
 */
function LimitdServer (options) {
  EventEmitter.call(this);
  var self = this;

  if (!options.db) {
    throw new TypeError('"db" is required');
  }

  this._config = _.extend({}, defaults, options);
  var configError = validateConfig(this._config);
  if (configError) {
    throw new Error(configError);
  }

  this._logger = logger(this._config.log_level);
  this._server = net.createServer(this._handler.bind(this));
  enableDestroy(this._server);

  this._server.on('error', function (err) {
    self.emit('error', err);
  });

  this._db = db(this._config.db);
  this._buckets = new Buckets(this._db, this._config);

  agent.init({
    'name': 'limitd'
  }, {
    'COLLECT_RESOURCE_USAGE': true,
    'STATSD_HOST': this._config.statsd_host,
    'METRICS_API_KEY': this._config.metrics_api_key,
    'ERROR_REPORTER_URL': this._config.error_reporter_url
  });
}

util.inherits(LimitdServer, EventEmitter);

LimitdServer.prototype._handler = function (socket) {
  var sockets_details = _.pick(socket, ['remoteAddress', 'remotePort']);
  var log = this._logger;

  socket.on('error', function (err) {
    log.debug(_.extend(sockets_details, {
      err: {
        code:    err.code,
        message: err.message
      }
    }), 'connection error');
  }).on('close', function () {
    log.debug(sockets_details, 'connection closed');
  });

  log.debug(sockets_details, 'connection accepted');

  var decoder = RequestDecoder({ protocol: this._config.protocol });

  decoder.on('error', function () {
    log.debug(sockets_details, 'unknown message format');
    return socket.end();
  });

  var response_writer = ResponseWriter({protocol: this._config.protocol});

  var request_handler = RequestHandler({
    protocol: this._config.protocol,
    buckets: this._buckets,
    logger: this._logger,
    write: (response) => {
      response_writer.write(response);
    }
  });

  response_writer.pipe(lps_encode())
                 .pipe(socket);

  socket.pipe(lps.decode())
        .pipe(decoder)
        .pipe(request_handler);
};

LimitdServer.prototype.start = function (done) {
  var self = this;
  var log = self._logger;

  self._server.listen(this._config.port, this._config.hostname, function(err) {
    if (err) {
      log.error(err, 'error starting server');
      self.emit('error', err);
      if (done) {
        done(err);
      }
      return;
    }

    var address = self._server.address();
    log.debug(address, 'server started');
    self.emit('started', address);
    if (done) {
      done(null, address);
    }
  });

  return this;
};

LimitdServer.prototype.stop = function () {
  var self = this;
  var log = self._logger;
  var address = self._server.address();

  var timeout = setTimeout(function () {
    self._server.destroy();
  }, 500);

  this._server.close(function() {
    clearTimeout(timeout);
    log.debug(address, 'server closed');
    self.emit('close');
  });
};

module.exports = LimitdServer;

<commit_msg>improve server close<commit_after>var EventEmitter = require('events').EventEmitter;

var util   = require('util');
var logger = require('./lib/logger');
var _      = require('lodash');
var net = require('net');
var Buckets = require('./lib/buckets');

var ResponseWriter = require('./lib/pipeline/response_writer');
var RequestHandler = require('./lib/pipeline/request_handler');
var RequestDecoder = require('./lib/pipeline/request_decoder');
var lps = require('length-prefixed-stream');
var lps_encode = require('./lib/lps_encode');
var validateConfig = require('./lib/config_validator');
var agent = require('auth0-instrumentation');

var db = require('./lib/db');
var enableDestroy = require('server-destroy');

var defaults = {
  port:      9231,
  hostname:  '0.0.0.0',
  log_level: 'info',
  protocol:  'protocol-buffers'
};

/*
 * Creates an instance of LimitdServer.
 *
 * Options:
 *
 *  - `db` the path to the database. Required.
 *  - `port` the port to listen to. Defaults to 9231.
 *  - `hostname` the hostname to bind to. Defaults to INADDR_ANY
 *  - `log_level` the verbosity of the logs. Defaults to 'info'.
 *  - `metrics_api_key`, the DataDog api key to log metrics to. Defaults to undefined.
 *
 */
function LimitdServer (options) {
  EventEmitter.call(this);
  var self = this;

  if (!options.db) {
    throw new TypeError('"db" is required');
  }

  this._config = _.extend({}, defaults, options);
  var configError = validateConfig(this._config);
  if (configError) {
    throw new Error(configError);
  }

  this._logger = logger(this._config.log_level);
  this._server = net.createServer(this._handler.bind(this));
  enableDestroy(this._server);

  this._server.on('error', function (err) {
    self.emit('error', err);
  });

  this._db = db(this._config.db);
  this._buckets = new Buckets(this._db, this._config);

  agent.init({
    'name': 'limitd'
  }, {
    'COLLECT_RESOURCE_USAGE': true,
    'STATSD_HOST': this._config.statsd_host,
    'METRICS_API_KEY': this._config.metrics_api_key,
    'ERROR_REPORTER_URL': this._config.error_reporter_url
  });
}

util.inherits(LimitdServer, EventEmitter);

LimitdServer.prototype._handler = function (socket) {
  var sockets_details = _.pick(socket, ['remoteAddress', 'remotePort']);
  var log = this._logger;

  socket.on('error', function (err) {
    log.debug(_.extend(sockets_details, {
      err: {
        code:    err.code,
        message: err.message
      }
    }), 'connection error');
  }).on('close', function () {
    log.debug(sockets_details, 'connection closed');
  });

  log.debug(sockets_details, 'connection accepted');

  var decoder = RequestDecoder({ protocol: this._config.protocol });

  decoder.on('error', function () {
    log.debug(sockets_details, 'unknown message format');
    return socket.end();
  });

  var response_writer = ResponseWriter({protocol: this._config.protocol});

  var request_handler = RequestHandler({
    protocol: this._config.protocol,
    buckets: this._buckets,
    logger: this._logger,
    write: (response) => {
      response_writer.write(response);
    }
  });

  response_writer.pipe(lps_encode())
                 .pipe(socket);

  socket.pipe(lps.decode())
        .pipe(decoder)
        .pipe(request_handler);
};

LimitdServer.prototype.start = function (done) {
  var self = this;
  var log = self._logger;

  self._server.listen(this._config.port, this._config.hostname, function(err) {
    if (err) {
      log.error(err, 'error starting server');
      self.emit('error', err);
      if (done) {
        done(err);
      }
      return;
    }

    var address = self._server.address();
    log.debug(address, 'server started');
    self.emit('started', address);
    if (done) {
      done(null, address);
    }
  });

  return this;
};

LimitdServer.prototype.stop = function () {
  var self = this;
  var log = self._logger;
  var address = self._server.address();

  this._server.destroy(function() {
    log.debug(address, 'server closed');
    self.emit('close');
  });
};

module.exports = LimitdServer;

<|endoftext|>


<commit_before>var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;

var CONTACTS_COLLECTION = "contacts";

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");

  // Initialize the app.
  var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
  });
});

// CONTACTS API ROUTES BELOW

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/contacts"
 *    GET: finds all contacts
 *    POST: creates a new contact
 */

app.get("/contacts", function(req, res) {
  db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get contacts.");
    } else {
      res.status(200).json(docs);
    }
  });
});

app.post("/contacts", function(req, res) {
  var newContact = req.body;
  newContact.createDate = new Date();

//  if (!(req.body.firstName || req.body.lastName)) {
//    handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
//  }

  db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to create new contact.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
});

/*  "/contacts/:id"
 *    GET: find contact by id
 *    PUT: update contact by id
 *    DELETE: deletes contact by id
 */

app.get("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to get contact");
    } else {
      res.status(200).json(doc);
    }
  });
});

app.get("/api/v1/test/:name", function(req, res) {
    console.log("Param: " + req.params.name);
    db.collection(CONTACTS_COLLECTION).find({ name: req.params.name }).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to list name");
        } else {
            res.status(200).json(doc);
        }
    });
});
//-----------------------------------------------
// API V1 -> SEARCH
//
app.get("/api/v1/search", function(req, res) {
	console.log("query source : "+req.query.source);
    if (req.query.source == "*" || ( typeof req.query.source == 'undefined')) { source = { $regex: /\w|/, $options:"i"} } else { source = req.query.source }
    if (req.query.name == "*" || (typeof req.query.name == 'undefined')) { name = { $regex: /\w|/, $options:"i"} } else { name = req.query.name }
//    if (typeof req.query.before == 'undefined')) { before = ObjectID(Math.floor((new Date('9999/12/31'))/1000).toString(16) + "0000000000000000") } else { before = ObjectID(Math.floor((new Date(req.query.before))/1000).toString(16) + "0000000000000000") }
//    if (typeof req.query.after == 'undefined')) { after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000") } else { after = ObjectID(Math.floor((new Date(req.query.after))/1000).toString(16) + "0000000000000000") }

	selection = { name: name, source: source } ;
	before = ObjectID(Math.floor((new Date('2999/12/31'))/1000).toString(16) + "0000000000000000");
	after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000");
	console.log("before = "+before+"  after : "+after);

    db.collection(CONTACTS_COLLECTION).find( { name: name, source: source } ).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find contact");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.put("/contacts/:id", function(req, res) {
  var updateDoc = req.body;
  delete updateDoc._id;

  db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to update contact");
    } else {
      res.status(204).end();
    }
  });
});

app.delete("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
    if (err) {
      handleError(res, err.message, "Failed to delete contact");
    } else {
      res.status(204).end();
    }
  });
});
<commit_msg>api date<commit_after>var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;

var CONTACTS_COLLECTION = "contacts";

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");

  // Initialize the app.
  var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
  });
});

// CONTACTS API ROUTES BELOW

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/contacts"
 *    GET: finds all contacts
 *    POST: creates a new contact
 */

app.get("/contacts", function(req, res) {
  db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get contacts.");
    } else {
      res.status(200).json(docs);
    }
  });
});

app.post("/contacts", function(req, res) {
  var newContact = req.body;
  newContact.createDate = new Date();

//  if (!(req.body.firstName || req.body.lastName)) {
//    handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
//  }

  db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to create new contact.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
});

/*  "/contacts/:id"
 *    GET: find contact by id
 *    PUT: update contact by id
 *    DELETE: deletes contact by id
 */

app.get("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to get contact");
    } else {
      res.status(200).json(doc);
    }
  });
});

app.get("/api/v1/test/:name", function(req, res) {
    console.log("Param: " + req.params.name);
    db.collection(CONTACTS_COLLECTION).find({ name: req.params.name }).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to list name");
        } else {
            res.status(200).json(doc);
        }
    });
});
//-----------------------------------------------
// API V1 -> SEARCH
//
app.get("/api/v1/search", function(req, res) {
	console.log("query source : "+req.query.source);
    if (req.query.source == "*" || ( typeof req.query.source == 'undefined')) { source = { $regex: /\w|/, $options:"i"} } else { source = req.query.source }
    if (req.query.name == "*" || (typeof req.query.name == 'undefined')) { name = { $regex: /\w|/, $options:"i"} } else { name = req.query.name }
//    if (typeof req.query.before == 'undefined')) { before = ObjectID(Math.floor((new Date('9999/12/31'))/1000).toString(16) + "0000000000000000") } else { before = ObjectID(Math.floor((new Date(req.query.before))/1000).toString(16) + "0000000000000000") }
//    if (typeof req.query.after == 'undefined')) { after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000") } else { after = ObjectID(Math.floor((new Date(req.query.after))/1000).toString(16) + "0000000000000000") }

	selection = { name: name, source: source } ;
	before = ObjectID(Math.floor((new Date('2100/12/31'))/1000).toString(16) + "0000000000000000");
	after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000");
	console.log("before = "+before+"  after : "+after);

    db.collection(CONTACTS_COLLECTION).find( { name: name, source: source } ).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find contact");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.put("/contacts/:id", function(req, res) {
  var updateDoc = req.body;
  delete updateDoc._id;

  db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to update contact");
    } else {
      res.status(204).end();
    }
  });
});

app.delete("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
    if (err) {
      handleError(res, err.message, "Failed to delete contact");
    } else {
      res.status(204).end();
    }
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var PORT = 8080;

var middleware= require('./middleware.js')

app.use(middleware.logger);

app.get('/about', middleware.requireAuthentication, function(request, response) {
    response.send('about');
});

app.use(express.static(__dirname + '/public'));

app.listen(PORT, function() {
    console.log('Express Server started on port ' + PORT);
});
<commit_msg>update for heroku<commit_after>var express = require('express');
var app = express();
var PORT = 8080;

var middleware= require('./middleware.js')

app.use(middleware.logger);

app.get('/about', middleware.requireAuthentication, function(request, response) {
    response.send('about');
});

app.use(express.static(__dirname));

app.listen(PORT, function() {
    console.log('Express Server started on port ' + PORT);
});
<|endoftext|>