<commit_before>'use strict'

var server = require('./server')
  , stream = require('stream')
  , request = require('../index')
  , tape = require('tape')

var s = server.createServer()

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

tape('test testPutBoolean', function(t) {
  s.on('/testPutBoolean', server.createPostValidator('true', 'application/json'))
  var opts = {
    method: 'PUT',
    uri: s.url + '/testPutBoolean',
    json: true,
    body: true
  }
  request(opts, function (err, resp, body) {
    t.equal(err, null)
    t.end()
  })
})

tape('test testPutNull', function(t) {
  s.on('/testPutNull', server.createPostValidator('null', 'application/json'))
  var opts = {
    method: 'PUT',
    uri: s.url + '/testPutNull',
    json: true,
    body: null
  }
  request(opts, function (err, resp, body) {
    t.equal(err, null)
    t.end()
  })
})

tape('cleanup', function(t) {
  s.close()
  t.end()
})
<commit_msg>More JSON request tests<commit_after>'use strict'

var server = require('./server')
  , stream = require('stream')
  , request = require('../index')
  , tape = require('tape')

var s = server.createServer()

tape('setup', function(t) {
  s.listen(s.port, function() {
    t.end()
  })
})

function testJSONValue(testId, value) {
  tape('test ' + testId, function(t) {
    var testUrl = '/' + testId
    s.on(testUrl, server.createPostValidator(JSON.stringify(value), 'application/json'))
    var opts = {
      method: 'PUT',
      uri: s.url + testUrl,
      json: true,
      body: value
    }
    request(opts, function (err, resp, body) {
      t.equal(err, null)
      t.end()
    })
  })
}

testJSONValue('jsonNull', null)
testJSONValue('jsonTrue', true)
testJSONValue('jsonFalse', false)
testJSONValue('jsonNumber', -289365.2938)
testJSONValue('jsonString', 'some string')
testJSONValue('jsonArray', ['value1', 2, null, 8925.53289, true, false, ['array'], { object: 'property' }])
testJSONValue('jsonObject', {
  trueProperty: true,
  falseProperty: false,
  numberProperty: -98346.34698,
  stringProperty: 'string',
  nullProperty: null,
  arrayProperty: ['array'],
  objectProperty: { object: 'property' }
})

tape('cleanup', function(t) {
  s.close()
  t.end()
})
<|endoftext|>


<commit_before>/*global describe, it, beforeEach */
/**
 * observe-plus.js - https://github.com/podefr/observe-plus
 * Copyright(c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 * MIT Licensed
 */
"use strict";

var chai = require("chai");
var expect = chai.expect;
var asap = require("asap");

var observeObject = require("../src/observe-plus").observe;

describe("GIVEN an observed object", function () {

    var pojo,
        observer,
        aggregatedEvents;

    function resetAggregatedEvents() {
        aggregatedEvents = [];
    }

    beforeEach(function () {
        pojo = {};
        observer = observeObject(pojo);
    });

    describe("WHEN observing newly added properties", function () {

        var dispose;

        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observe("add", function (ev) {
                aggregatedEvents.push([ev, "observer1"]);
            });
        });

        it("THEN shouldn't publish any event before a new property is added", function (done) {
            asap(function () {
                expect(aggregatedEvents.length).to.equal(0);
                done();
            });
        });

        describe("WHEN a new property is added", function () {
            beforeEach(function () {
                pojo.newProperty = "newValue";
            });

            it("THEN should publish a new event", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0],
                        observerName = aggregatedEvents[0][1];

                    expect(firstEvent.type).to.equal("add");
                    expect(firstEvent.name).to.equal("newProperty");
                    expect(firstEvent.object.newProperty).to.equal("newValue");
                    expect(observerName).to.equal("observer1");
                    done();
                });
            });

            it("THEN only published one event", function (done) {
                asap(function () {
                    expect(aggregatedEvents.length).to.equal(1);
                    done();
                });
            });

            describe("WHEN destroying", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.destroy();

                    pojo.anotherProperty = "value";
                });

                it("THEN doesn't publish events anymore", function (done) {
                    asap(function () {
                        expect(aggregatedEvents.length).to.equal(0);
                        done();
                    });
                });
            });

            describe("WHEN the property is modified", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.observe("update", function (ev) {
                        aggregatedEvents.push([ev]);
                    });
                    pojo.newProperty = "updatedValue";
                });

                it("THEN calls the observer with the updated event", function (done) {
                    asap(function () {
                        var firstEvent = aggregatedEvents[0][0];

                        expect(firstEvent.type).to.equal("update");
                        expect(firstEvent.name).to.equal("newProperty");
                        expect(firstEvent.object.newProperty).to.equal("updatedValue");
                        expect(firstEvent.oldValue).to.equal("newValue");
                        done();
                    });
                });
            });

            describe("WHEN the property is deleted", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.observe("delete", function (ev) {
                        aggregatedEvents.push([ev]);
                    });
                    delete pojo.newProperty;
                });

                it("THEN calls the observer with undefined and the old value", function (done) {
                    asap(function () {
                        var firstEvent = aggregatedEvents[0][0];

                        expect(firstEvent.name).to.equal("newProperty");
                        expect(firstEvent.object.newProperty).to.be.undefined;
                        expect(firstEvent.oldValue).to.equal("newValue");
                        done();
                    });
                });
            });
        });

        describe("WHEN a new observer is added", function () {
            var dispose2;

            beforeEach(function () {
                resetAggregatedEvents();
                dispose2 = observer.observe("add", function (ev) {
                    aggregatedEvents.push([ev, "observer2"]);
                });
            });

            describe("WHEN an observer is disposed of", function () {
                var isDisposedOf = false;

                beforeEach(function () {
                    isDisposedOf = dispose();
                });

                describe("WHEN a new property is added", function () {
                    beforeEach(function () {
                        resetAggregatedEvents();
                        pojo.newProperty = {};
                    });

                    it("THEN doesn't call the disposed observer anymore", function (done) {
                        asap(function () {
                            var numberOfCallbacksCalled = aggregatedEvents.length,
                                firstObserverName = aggregatedEvents[0][1];

                            expect(numberOfCallbacksCalled).to.equal(1);
                            expect(firstObserverName).to.equal("observer2");

                            done();
                        });
                    });

                    it("THEN tells if the observer can be disposed of", function () {
                        expect(isDisposedOf).to.be.true;
                    });

                    describe("WHEN an observer has been disposed of", function () {
                        beforeEach(function () {
                            isDisposedOf = dispose();
                        });

                        it("THEN tells that it can't be disposed of anymore", function (done) {
                            expect(isDisposedOf).to.be.false;
                            done();
                        });
                    });
                });
            });
        });
    });

    describe("WHEN observing specific properties", function () {
        var dispose;

        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeValue("newProperty", function (ev) {
                aggregatedEvents.push([ev]);
            });
            pojo.newProperty = "newValue";
        });

        it("THEN publishes an event with the new value and the old value", function (done) {
            asap(function () {
                var firstEvent = aggregatedEvents[0][0];
                expect(firstEvent.name).to.equal("newProperty");
                expect(firstEvent.object.newProperty).to.equal("newValue");
                expect(firstEvent.oldValue).to.be.undefined;
                done();
            });
        });
    });

    describe("WHEN observing nested properties", function () {
        beforeEach(function () {
            resetAggregatedEvents();
            observer.observeValue("newProperty.nested.property", function (ev) {
                aggregatedEvents.push([ev]);
            });
            pojo.newProperty = {
                nested: {
                    property: true
                }
            };
        });

        it("Then publishes an event", function (done) {
             asap(function () {
                var firstEvent = aggregatedEvents[0][0];
                 expect(firstEvent.name).to.equal("newProperty.nested.property");
                 expect(firstEvent.object.newProperty.nested.property).to.be.true;
                 done();
             });
        });

        describe("WHEN the nested property is modified", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                pojo.newProperty.nested.property = false;
            });

            it("THEN publishes an update event", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0];
                    expect(firstEvent.name).to.equal("newProperty.nested.property");
                    expect(firstEvent.object.newProperty.nested.property).to.be.false;
                    expect(firstEvent.type).to.equal("update");
                    done();
                });
            });

            describe("WHEN a parent object is replaced and the value of the observed nested property changes", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    pojo.newProperty.nested = {
                        property: true
                    };
                });

                it("THEN triggers a new event", function (done) {
                    asap(function () {
                        var event = aggregatedEvents[0][0];
                        expect(event.type).to.equal("update");
                        expect(event.object).to.equal(pojo);
                        expect(event.name).to.equal("newProperty.nested.property");
                        expect(event.oldValue).to.be.false;
                        done();
                    });
                });
            });

            describe("WHEN a parent object is replaced and the value of the observed nested property doesn't change", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    pojo.newProperty.nested = {
                        property: false
                    };
                });

                it("THEN doesn't trigger an event", function (done) {
                    asap(function () {
                        expect(aggregatedEvents[0]).to.be.undefined;
                        done();
                    });
                });
            });
        });

        describe("WHEN the nested property is deleted ", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                delete pojo.newProperty.nested;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0];
                    expect(firstEvent).to.eql({
                        type: "delete",
                        name: "newProperty.nested.property",
                        object: pojo,
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN a parent object of a nested property is deleted", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                delete pojo.newProperty;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0];
                    expect(firstEvent).to.eql({
                        type: "delete",
                        name: "newProperty.nested.property",
                        object: pojo,
                        oldValue: true
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing only once", function () {
        var dispose;
        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeOnce("add", function (ev) {
                aggregatedEvents.push([ev]);
            });
        });

        describe("WHEN the property is added", function () {
            beforeEach(function () {
                pojo.newProperty = "value";
            });

            it("THEN calls the observer", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0];
                    expect(firstEvent.name).to.equal("newProperty");
                    expect(firstEvent.object.newProperty).to.equal("value");
                    done();
                });
            });

            it("THEN is disposed of", function (done) {
                asap(function () {
                    expect(dispose()).to.be.false;
                    done();
                });
            });
        });
    });

    describe("WHEN observing a property only once", function () {
        var dispose;
        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeValueOnce("newProperty", function (ev) {
                aggregatedEvents.push([ev]);
            });
            pojo.newProperty = "value";
        });

        it("THEN calls the observer", function (done) {
            asap(function () {
                var firstEvent = aggregatedEvents[0][0];
                expect(firstEvent.name).to.equal("newProperty");
                expect(firstEvent.object.newProperty).to.equal("value");
                done();
            });
        });

        it("THEN is disposed of", function (done) {
            asap(function () {
                expect(dispose()).to.be.false;
                done();
            });
        });
    });

    describe("WHEN pausing the updates", function () {
        beforeEach(function () {
            observer.observeValue("newProperty", function (ev) {
                aggregatedEvents.push([ev]);
            });
            observer.pause();
        });

        describe("WHEN a property changes", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                pojo.newProperty = "value";
                pojo.newProperty = "newValue";
                delete pojo.newProperty;
            });

            it("THEN the observers aren't called", function (done) {
                asap(function () {
                    expect(aggregatedEvents.length).to.equal(0);
                    done();
                });
            });

            describe("WHEN resuming publishing the updates", function () {
                beforeEach(function () {
                    observer.resume();
                });

                it("THEN calls all the observers in order", function (done) {
                    asap(function () {
                        var firstEvent = aggregatedEvents[0][0],
                            secondEvent = aggregatedEvents[1][0],
                            thirdEvent = aggregatedEvents[2][0];

                        expect(firstEvent.type).to.equal("add");
                        expect(secondEvent.type).to.equal("update");
                        expect(thirdEvent.type).to.equal("delete");
                        done();
                    });
                });

                describe("WHEN the updates are paused and resumed again", function () {
                    beforeEach(function () {
                        resetAggregatedEvents();
                        observer.pause();
                        pojo.newProperty = "lastValue";
                        observer.resume();
                    });

                    it("THEN only publishes the new event", function (done) {
                        asap(function () {
                            expect(aggregatedEvents.length).to.equal(1);
                            done();
                        });
                    });
                });
            });
        });
    });
});<commit_msg>removing aggregateEvents<commit_after>/*global describe, it, beforeEach */
/**
 * observe-plus.js - https://github.com/podefr/observe-plus
 * Copyright(c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 * MIT Licensed
 */
"use strict";

var chai = require("chai");
var expect = chai.expect;
var asap = require("asap");
var sinon = require("sinon");

var observeObject = require("../src/observe-plus").observe;

describe("GIVEN an observed object", function () {

    var pojo,
        observer,
        aggregatedEvents;

    function resetAggregatedEvents() {
        aggregatedEvents = [];
    }

    beforeEach(function () {
        pojo = {};
        observer = observeObject(pojo);
    });

    describe("WHEN observing newly added properties", function () {

        var dispose, spy;

        beforeEach(function () {
            resetAggregatedEvents();
            spy = sinon.spy();
            dispose = observer.observe("add", spy);
        });

        afterEach(function () {
            spy.reset();
        });

        it("THEN shouldn't publish any event before a new property is added", function (done) {
            asap(function () {
                expect(spy.callCount).to.equal(0);
                done();
            });
        });

        describe("WHEN a new property is added", function () {
            beforeEach(function () {
                pojo.newProperty = "newValue";
            });

            it("THEN should publish a new event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: "add",
                        name: "newProperty",
                        object: pojo
                    });
                    done();
                });
            });

            it("THEN only published one event", function (done) {
                asap(function () {
                    expect(spy.callCount).to.equal(1);
                    done();
                });
            });

            describe("WHEN destroying", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.destroy();

                    pojo.anotherProperty = "value";
                });

                it("THEN doesn't publish events anymore", function (done) {
                    asap(function () {
                        expect(spy.callCount).to.equal(1);
                        done();
                    });
                });
            });

            describe("WHEN the property is modified", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.observe("update", spy);
                    pojo.newProperty = "updatedValue";
                });

                it("THEN calls the observer with the updated event", function (done) {
                    asap(function () {
                        expect(spy.secondCall.args[0]).to.eql({
                            type: "update",
                            name: "newProperty",
                            object: pojo,
                            oldValue: "newValue"
                        });
                        done();
                    });
                });
            });

            describe("WHEN the property is deleted", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    observer.observe("delete", spy);
                    delete pojo.newProperty;
                });

                it("THEN calls the observer with undefined and the old value", function (done) {
                    asap(function () {
                        expect(spy.secondCall.args[0]).to.eql({
                            type: "delete",
                            name: "newProperty",
                            object: pojo,
                            oldValue: "newValue"
                        });
                        done();
                    });
                });
            });
        });

        describe("WHEN a new observer is added", function () {
            var dispose2;

            beforeEach(function () {
                resetAggregatedEvents();
                dispose2 = observer.observe("add", spy);
            });

            describe("WHEN an observer is disposed of", function () {
                var isDisposedOf = false;

                beforeEach(function () {
                    isDisposedOf = dispose();
                });

                describe("WHEN a new property is added", function () {
                    beforeEach(function () {
                        resetAggregatedEvents();
                        pojo.newProperty = {};
                    });

                    it("THEN doesn't call the disposed observer anymore", function (done) {
                        asap(function () {
                            expect(spy.callCount).to.equal(1);

                            done();
                        });
                    });

                    it("THEN tells if the observer can be disposed of", function () {
                        expect(isDisposedOf).to.be.true;
                    });

                    describe("WHEN an observer has been disposed of", function () {
                        beforeEach(function () {
                            isDisposedOf = dispose();
                        });

                        it("THEN tells that it can't be disposed of anymore", function (done) {
                            expect(isDisposedOf).to.be.false;
                            done();
                        });
                    });
                });
            });
        });
    });

    describe("WHEN observing specific properties", function () {
        var dispose, spy;

        beforeEach(function () {
            resetAggregatedEvents();
            spy = sinon.spy();
            dispose = observer.observeValue("newProperty", spy);
            pojo.newProperty = "newValue";
        });

        it("THEN publishes an event with the new value and the old value", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "add",
                    name: "newProperty",
                    object: pojo,
                    oldValue: undefined
                });
                done();
            });
        });
    });

    describe("WHEN observing nested properties", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            resetAggregatedEvents();
            observer.observeValue("newProperty.nested.property", spy);
            pojo.newProperty = {
                nested: {
                    property: true
                }
            };
        });

        it("Then publishes an event", function (done) {
             asap(function () {
                 expect(spy.firstCall.args[0]).to.eql({
                     type: "add",
                     object: pojo,
                     name: "newProperty.nested.property",
                     oldValue: undefined
                 });
                 done();
             });
        });

        describe("WHEN the nested property is modified", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                pojo.newProperty.nested.property = false;
            });

            it("THEN publishes an update event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "update",
                        object: pojo,
                        name: "newProperty.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });

            describe("WHEN a parent object is replaced and the value of the observed nested property changes", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    pojo.newProperty.nested = {
                        property: true
                    };
                });

                it("THEN triggers a new event", function (done) {
                    asap(function () {
                        expect(spy.secondCall.args[0]).to.eql({
                            type: "update",
                            object: pojo,
                            name: "newProperty.nested.property",
                            oldValue: true
                        });
                        done();
                    });
                });
            });

            describe("WHEN a parent object is replaced and the value of the observed nested property doesn't change", function () {
                beforeEach(function () {
                    resetAggregatedEvents();
                    pojo.newProperty.nested = {
                        property: false
                    };
                });

                it("THEN doesn't trigger an event", function (done) {
                    asap(function () {
                        expect(spy.callCount).to.equal(2);
                        done();
                    });
                });
            });
        });

        describe("WHEN the nested property is deleted ", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                delete pojo.newProperty.nested;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        name: "newProperty.nested.property",
                        object: pojo,
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN a parent object of a nested property is deleted", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                delete pojo.newProperty;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        name: "newProperty.nested.property",
                        object: pojo,
                        oldValue: true
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing only once", function () {
        var dispose;
        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeOnce("add", function (ev) {
                aggregatedEvents.push([ev]);
            });
        });

        describe("WHEN the property is added", function () {
            beforeEach(function () {
                pojo.newProperty = "value";
            });

            it("THEN calls the observer", function (done) {
                asap(function () {
                    var firstEvent = aggregatedEvents[0][0];
                    expect(firstEvent.name).to.equal("newProperty");
                    expect(firstEvent.object.newProperty).to.equal("value");
                    done();
                });
            });

            it("THEN is disposed of", function (done) {
                asap(function () {
                    expect(dispose()).to.be.false;
                    done();
                });
            });
        });
    });

    describe("WHEN observing a property only once", function () {
        var dispose;
        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeValueOnce("newProperty", function (ev) {
                aggregatedEvents.push([ev]);
            });
            pojo.newProperty = "value";
        });

        it("THEN calls the observer", function (done) {
            asap(function () {
                var firstEvent = aggregatedEvents[0][0];
                expect(firstEvent.name).to.equal("newProperty");
                expect(firstEvent.object.newProperty).to.equal("value");
                done();
            });
        });

        it("THEN is disposed of", function (done) {
            asap(function () {
                expect(dispose()).to.be.false;
                done();
            });
        });
    });

    describe("WHEN pausing the updates", function () {
        beforeEach(function () {
            observer.observeValue("newProperty", function (ev) {
                aggregatedEvents.push([ev]);
            });
            observer.pause();
        });

        describe("WHEN a property changes", function () {
            beforeEach(function () {
                resetAggregatedEvents();
                pojo.newProperty = "value";
                pojo.newProperty = "newValue";
                delete pojo.newProperty;
            });

            it("THEN the observers aren't called", function (done) {
                asap(function () {
                    expect(aggregatedEvents.length).to.equal(0);
                    done();
                });
            });

            describe("WHEN resuming publishing the updates", function () {
                beforeEach(function () {
                    observer.resume();
                });

                it("THEN calls all the observers in order", function (done) {
                    asap(function () {
                        var firstEvent = aggregatedEvents[0][0],
                            secondEvent = aggregatedEvents[1][0],
                            thirdEvent = aggregatedEvents[2][0];

                        expect(firstEvent.type).to.equal("add");
                        expect(secondEvent.type).to.equal("update");
                        expect(thirdEvent.type).to.equal("delete");
                        done();
                    });
                });

                describe("WHEN the updates are paused and resumed again", function () {
                    beforeEach(function () {
                        resetAggregatedEvents();
                        observer.pause();
                        pojo.newProperty = "lastValue";
                        observer.resume();
                    });

                    it("THEN only publishes the new event", function (done) {
                        asap(function () {
                            expect(aggregatedEvents.length).to.equal(1);
                            done();
                        });
                    });
                });
            });
        });
    });
});<|endoftext|>


<commit_before>var Attributes = require('../lib/waterline-schema/attributes'),
    assert = require('assert');

describe('Attributes', function() {

  describe('with automatic attribute flags', function() {
    var collection;

    before(function() {
      collection = function() {};
      collection.prototype = {
        tableName: 'FOO',
        autoPK: false,
        autoCreatedAt: false,
        autoUpdatedAt: false,
        attributes: {
          foo: 'string',
          bar: 'string',
          fn: function() {}
        }

      };
    });

    it('should build an attributes definition containing two keys', function() {
      var obj = new Attributes({ foo: collection });

      assert(obj.foo);
      assert(Object.keys(obj.foo.attributes).length === 2);
      assert(obj.foo.attributes.foo);
      assert(obj.foo.attributes.bar);
    });

    it('should strip functions', function() {
      var obj = new Attributes({ foo: collection });
      assert(!obj.foo.attributes.fn);
    });

    it('should set defaults for adapters', function() {
      var obj = new Attributes({ foo: collection });
      assert(obj.foo.adapter === '');
    });
  });

  describe('with automatic attribute flags not set', function() {
    var collection;

    before(function() {
      collection = function() {};
      collection.prototype = {
        tableName: 'FOO',
        attributes: {
          foo: 'string',
          bar: 'string',
          fn: function() {}
        }

      };
    });

    it('should add auto attributes to the definition', function() {
      var obj = new Attributes({ foo: collection });

      assert(obj.foo);
      assert(Object.keys(obj.foo.attributes).length === 5);
      assert(obj.foo.attributes.foo);
      assert(obj.foo.attributes.bar);
      assert(obj.foo.attributes.id);
      assert(obj.foo.attributes.createdAt);
      assert(obj.foo.attributes.updatedAt);
    });

    it('should inject flags into the collection', function() {
      var obj = new Attributes({ foo: collection });

      assert(collection.prototype.autoPK);
      assert(collection.prototype.autoCreatedAt);
      assert(collection.prototype.autoUpdatedAt);
    });

    it('should normalize tableName to identity', function() {
      var obj = new Attributes({ foo: collection });

      assert(collection.prototype.identity === 'foo');
    });
  });

});
<commit_msg>add auto attribute checks<commit_after>var Attributes = require('../lib/waterline-schema/attributes'),
    assert = require('assert');

describe('Attributes', function() {

  describe('with automatic attribute flags', function() {
    var collection;

    before(function() {
      collection = function() {};
      collection.prototype = {
        tableName: 'FOO',
        autoPK: false,
        autoCreatedAt: false,
        autoUpdatedAt: false,
        attributes: {
          foo: 'string',
          bar: 'string',
          fn: function() {}
        }
      };
    });

    it('should build an attributes definition containing two keys', function() {
      var obj = new Attributes({ foo: collection });

      assert(obj.foo);
      assert(Object.keys(obj.foo.attributes).length === 2);
      assert(obj.foo.attributes.foo);
      assert(obj.foo.attributes.bar);
    });

    it('should strip functions', function() {
      var obj = new Attributes({ foo: collection });
      assert(!obj.foo.attributes.fn);
    });

    it('should set defaults for adapters', function() {
      var obj = new Attributes({ foo: collection });
      assert(obj.foo.adapter === '');
    });
  });

  describe('with automatic attribute flags not set', function() {
    var collection;

    before(function() {
      collection = function() {};
      collection.prototype = {
        tableName: 'FOO',
        attributes: {
          foo: 'string',
          bar: 'string',
          fn: function() {}
        }
      };
    });

    it('should add auto attributes to the definition', function() {
      var obj = new Attributes({ foo: collection });
      assert(obj.foo);
      assert(Object.keys(obj.foo.attributes).length === 5);
      assert(obj.foo.attributes.foo);
      assert(obj.foo.attributes.bar);
      assert(obj.foo.attributes.id);
      assert(obj.foo.attributes.createdAt);
      assert(obj.foo.attributes.updatedAt);
    });

    it('should inject flags into the collection', function() {
      var obj = new Attributes({ foo: collection });
      assert(collection.prototype.autoPK);
      assert(collection.prototype.autoCreatedAt);
      assert(collection.prototype.autoUpdatedAt);
    });

    it('should normalize tableName to identity', function() {
      var obj = new Attributes({ foo: collection });
      assert(collection.prototype.identity === 'foo');
    });

    it('should add a primary key field', function() {
      var obj = new Attributes({ foo: collection });
      assert(obj.foo.attributes.id);
      assert(obj.foo.attributes.id.primaryKey);
      assert(obj.foo.attributes.id.unique);
    });

    it('should add in timestamps', function() {
      var obj = new Attributes({ foo: collection });
      assert(obj.foo.attributes.createdAt);
      assert(obj.foo.attributes.updatedAt);
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var BookmarkHandler = require(path + '/app/controllers/bookmarkHandler.server.js');
var UpvoteHandler = require(path + '/app/controllers/upvoteHandler.server.js');
var ArticleHandler = require(path + '/app/controllers/artikelHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();
	var bookmarkHandler = new BookmarkHandler();
    var upvoteHandler = new UpvoteHandler();
    var articleHandler = new ArticleHandler();

	app.route('/').get(isLoggedIn, function (req, res) {
		res.sendFile(path + '/public/index.html');
	});

	app.route('/login').get(function (req, res) {
		res.sendFile(path + '/public/homepage.html');
	});

	app.route('/logout').get(function (req, res) {
		req.logout();
		res.redirect('/login');
	});

	app.route('/profile').get(isLoggedIn, function (req, res) {
		res.sendFile(path + '/public/profile.html');
	});

	app.route('/artikel').get(isLoggedIn, function(req, res) {
		res.sendFile(path + '/public/kumpulanartikel.html');

	});

	app.route('/api/:id').get(isLoggedIn, function (req, res) {
		res.json(req.user.twitter);
	});

	app.route('/auth/twitter').get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback').get(passport.authenticate('twitter', {
		successRedirect: '/',
		failureRedirect: '/login'
	}));

	app.route('/api/:id/tanaman')
		.get(isLoggedIn);

	app.route('/api/:id/artikel')
		.get(isLoggedIn, articleHandler.getArticles);

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);

	app.route('/api/:id/bookmark')
		.get(isLoggedIn, bookmarkHandler.getBookmarks)
		.post(isLoggedIn, bookmarkHandler.addBookmark)
		.delete(isLoggedIn, bookmarkHandler.removeBookmark);

    app.route('/api/:id/upvote')
        .get(isLoggedIn, upvoteHandler.getUpvotes)
        .post(isLoggedIn, upvoteHandler.addUpvote)
        .delete(isLoggedIn, upvoteHandler.removeUpvote);

	// =====================================
    // FACEBOOK ROUTES =====================
    // =====================================
    // route for facebook authentication and login
    /*
    app.route('/auth/facebook')
    	.get(passport.authenticate('facebook'));

    // handle the callback after facebook has authenticated the user
    app.route('/auth/facebook/callback')
    	.get(passport.authenticate('facebook', {
            failureRedirect : '/login'
        }),
		function(req, res) {
			res.redirect('/');
		}
        );
	*/
    // =====================================
    // TWITTER ROUTES ======================
    // =====================================
    // route for twitter authentication and login
    /*
    app.get('/auth/twitter', passport.authenticate('twitter'));

    // handle the callback after twitter has authenticated the user
    app.get('/auth/twitter/callback',
        passport.authenticate('twitter', {
            successRedirect : '/',
            failureRedirect : '/login'
        }));
    */
};
<commit_msg>Route untuk api tanaman<commit_after>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var BookmarkHandler = require(path + '/app/controllers/bookmarkHandler.server.js');
var UpvoteHandler = require(path + '/app/controllers/upvoteHandler.server.js');
var ArticleHandler = require(path + '/app/controllers/artikelHandler.server.js');
var TanamanHandler = require(path + '/app/controllers/tanamanHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.redirect('/login');
		}
	}

	var clickHandler = new ClickHandler();
	var bookmarkHandler = new BookmarkHandler();
    var upvoteHandler = new UpvoteHandler();
    var articleHandler = new ArticleHandler();
	var tanamanHandler = new TanamanHandler();

	app.route('/').get(isLoggedIn, function (req, res) {
		res.sendFile(path + '/public/index.html');
	});

	app.route('/login').get(function (req, res) {
		res.sendFile(path + '/public/homepage.html');
	});

	app.route('/logout').get(function (req, res) {
		req.logout();
		res.redirect('/login');
	});

	app.route('/profile').get(isLoggedIn, function (req, res) {
		res.sendFile(path + '/public/profile.html');
	});

	app.route('/artikel').get(isLoggedIn, function(req, res) {
		res.sendFile(path + '/public/kumpulanartikel.html');

	});

	app.route('/api/:id').get(isLoggedIn, function (req, res) {
		res.json(req.user.twitter);
	});

	app.route('/auth/twitter').get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback').get(passport.authenticate('twitter', {
		successRedirect: '/',
		failureRedirect: '/login'
	}));

	app.route('/api/:id/tanaman')
		.get(isLoggedIn, tanamanHandler.getTanaman);

	app.route('/api/:id/artikel')
		.get(isLoggedIn, articleHandler.getArticles);

	app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);

	app.route('/api/:id/bookmark')
		.get(isLoggedIn, bookmarkHandler.getBookmarks)
		.post(isLoggedIn, bookmarkHandler.addBookmark)
		.delete(isLoggedIn, bookmarkHandler.removeBookmark);

    app.route('/api/:id/upvote')
        .get(isLoggedIn, upvoteHandler.getUpvotes)
        .post(isLoggedIn, upvoteHandler.addUpvote)
        .delete(isLoggedIn, upvoteHandler.removeUpvote);

	// =====================================
    // FACEBOOK ROUTES =====================
    // =====================================
    // route for facebook authentication and login
    /*
    app.route('/auth/facebook')
    	.get(passport.authenticate('facebook'));

    // handle the callback after facebook has authenticated the user
    app.route('/auth/facebook/callback')
    	.get(passport.authenticate('facebook', {
            failureRedirect : '/login'
        }),
		function(req, res) {
			res.redirect('/');
		}
        );
	*/
    // =====================================
    // TWITTER ROUTES ======================
    // =====================================
    // route for twitter authentication and login
    /*
    app.get('/auth/twitter', passport.authenticate('twitter'));

    // handle the callback after twitter has authenticated the user
    app.get('/auth/twitter/callback',
        passport.authenticate('twitter', {
            successRedirect : '/',
            failureRedirect : '/login'
        }));
    */
};
<|endoftext|>


<commit_before>'use strict';

const { extractSimpleIds } = require('../../../database');

// Returns database adapter's input
const getCommandInput = function ({
  command,
  args: {
    orderBy,
    limit,
    offset,
    newData,
    filter,
    deletedIds,
  },
  dryrun: { newInput = {} },
  modelName,
}) {
  const commandA = getCommand({ command, newInput });
  const filterA = newInput.filter || filter || {};
  const filterIds = extractSimpleIds({ filter: filterA });

  const commandInput = {
    modelName,
    filter: filterA,
    filterIds,
    deletedIds,
    newData,
    orderBy,
    limit,
    offset,
  };

  return { command: commandA, commandInput };
};

const getCommand = function ({ command, newInput }) {
  // Fake input during dry runs
  if (newInput.command) { return newInput.command; }

  // `patch` command behaves like `replace`, so we simplify adapters here
  if (command === 'patch') { return 'replace'; }

  return command;
};

module.exports = {
  getCommandInput,
};
<commit_msg>Pass command to database adapters<commit_after>'use strict';

const { extractSimpleIds } = require('../../../database');

// Returns database adapter's input
const getCommandInput = function ({
  command,
  args: {
    orderBy,
    limit,
    offset,
    newData,
    filter,
    deletedIds,
  },
  dryrun: { newInput = {} },
  modelName,
}) {
  const commandA = getCommand({ command, newInput });
  const filterA = newInput.filter || filter || {};
  const filterIds = extractSimpleIds({ filter: filterA });

  const commandInput = {
    command,
    modelName,
    filter: filterA,
    filterIds,
    deletedIds,
    newData,
    orderBy,
    limit,
    offset,
  };

  return { command: commandA, commandInput };
};

const getCommand = function ({ command, newInput }) {
  // Fake input during dry runs
  if (newInput.command) { return newInput.command; }

  // `patch` command behaves like `replace`, so we simplify adapters here
  if (command === 'patch') { return 'replace'; }

  return command;
};

module.exports = {
  getCommandInput,
};
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var formatter = require('../../../../formatter');
var clickableTemplate = require('./item-clickable-template.tpl');
var unclickableTemplate = require('./item-unclickable-template.tpl');

/**
 * Category list item view
 */
module.exports = cdb.core.View.extend({
  tagName: 'li',
  className: 'CDB-Widget-listItem',

  events: {
    'click .js-button': '_onItemClick'
  },

  initialize: function (options) {
    this.widgetModel = this.options.widgetModel;
    this.dataviewModel = this.options.dataviewModel;
    this._initBinds();
  },

  render: function () {
    var name = this.model.get('name');
    var value = this.model.get('value');
    var template = this.model.get('agg') || this.widgetModel.isLocked()
      ? unclickableTemplate
      : clickableTemplate;

    this.$el.html(
      template({
        customColor: this.widgetModel.isAutoStyle(),
        isAggregated: this.model.get('agg'),
        name: name,
        value: value,
        formattedValue: formatter.formatNumber(value),
        percentage: ((value / this.dataviewModel.get('max')) * 100),
        color: this.widgetModel.autoStyler.colors.getColorByCategory(name),
        isDisabled: !this.model.get('selected') ? 'is-disabled' : '',
        prefix: this.widgetModel.get('prefix'),
        suffix: this.widgetModel.get('suffix')
      })
    );

    return this;
  },

  _initBinds: function () {
    this.model.bind('change', this.render, this);
    this.widgetModel.bind('change:search change:isAutoStyle change:prefix change:suffix', this.render, this);
    this.dataviewModel.bind('change:autoStyle', this.render, this);
    this.add_related_model(this.widgetModel);
  },

  _onItemClick: function () {
    this.trigger('itemClicked', this.model, this);
  }

});
<commit_msg>removes isAutoStyle event<commit_after>var cdb = require('cartodb.js');
var formatter = require('../../../../formatter');
var clickableTemplate = require('./item-clickable-template.tpl');
var unclickableTemplate = require('./item-unclickable-template.tpl');

/**
 * Category list item view
 */
module.exports = cdb.core.View.extend({
  tagName: 'li',
  className: 'CDB-Widget-listItem',

  events: {
    'click .js-button': '_onItemClick'
  },

  initialize: function (options) {
    this.widgetModel = this.options.widgetModel;
    this.dataviewModel = this.options.dataviewModel;
    this._initBinds();
  },

  render: function () {
    var name = this.model.get('name');
    var value = this.model.get('value');
    var template = this.model.get('agg') || this.widgetModel.isLocked()
      ? unclickableTemplate
      : clickableTemplate;

    this.$el.html(
      template({
        customColor: this.widgetModel.isAutoStyle(),
        isAggregated: this.model.get('agg'),
        name: name,
        value: value,
        formattedValue: formatter.formatNumber(value),
        percentage: ((value / this.dataviewModel.get('max')) * 100),
        color: this.widgetModel.autoStyler.colors.getColorByCategory(name),
        isDisabled: !this.model.get('selected') ? 'is-disabled' : '',
        prefix: this.widgetModel.get('prefix'),
        suffix: this.widgetModel.get('suffix')
      })
    );

    return this;
  },

  _initBinds: function () {
    this.model.bind('change', this.render, this);
    this.widgetModel.bind('change:search change:prefix change:suffix', this.render, this);
    this.dataviewModel.bind('change:autoStyle', this.render, this);
    this.add_related_model(this.widgetModel);
  },

  _onItemClick: function () {
    this.trigger('itemClicked', this.model, this);
  }

});
<|endoftext|>


<commit_before>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')
, hash = require('hashish')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  _.bus = self // fix this hack!
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'
  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta === 'module_map') { // add map
      map = data
      self.map = data
      self.build()
    } else if (!data.client_id) { // pass through to out
      if (self.client_id) data.id = self.client_id
      self.send(data)
    } else if (data.id) {
      console.log('send to '+id)
    }
  }

  this.build = function () { // loadModule with mods from map array
    if (!map) throw new Error('no map')
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.eachSeries(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting ' + conn[key])

      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    if (self.scope==='server') _[mod.id.toUpperCase()] = require(mod.filePath)
    if (self.scope==='client') {
      _[mod.id.toUpperCase()] = require(mod.id)
    }

    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].render(mod.html)
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------

}
<commit_msg>logging global.process in brico for debugging<commit_after>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')
, hash = require('hashish')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  _.bus = self // fix this hack!
  telepath(this)

  // detect if running in node or in browser
  console.dir(global.process)
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'
  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta === 'module_map') { // add map
      map = data
      self.map = data
      self.build()
    } else if (!data.client_id) { // pass through to out
      if (self.client_id) data.id = self.client_id
      self.send(data)
    } else if (data.id) {
      console.log('send to '+id)
    }
  }

  this.build = function () { // loadModule with mods from map array
    if (!map) throw new Error('no map')
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.eachSeries(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting ' + conn[key])

      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    if (self.scope==='server') _[mod.id.toUpperCase()] = require(mod.filePath)
    if (self.scope==='client') {
      _[mod.id.toUpperCase()] = require(mod.id)
    }

    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].render(mod.html)
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------

}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Apr 13 2014 16:32:02 GMT-0300 (ART)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      '../lib/*.js',
      '../src/*.js',
      './*_test.js',
      'fixtures/*.html'
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.html': ['html2js']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<commit_msg>Test suite: Now the main.js file loads before all the other files<commit_after>// Karma configuration
// Generated on Sun Apr 13 2014 16:32:02 GMT-0300 (ART)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      '../lib/*.js',
      '../src/main.js',
      '../src/*.js',
      './*_test.js',
      'fixtures/*.html'
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.html': ['html2js']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.render('login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll.poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{poll:poll});
			})
		})
		.delete(function (req, res) {
			console.log(req);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				poll.remove();
				res.render("profile",{user:req.user});
			})
		});

	app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.render("poll",{poll:poll});
				})
				//console.log(poll.poll.choices);
			});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

	app.route('/createpoll')
		.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<commit_msg>displaying polls<commit_after>'use strict';

var User = require('../models/users');
var Poll = require('../models/polls');
var Choice = require('../models/choices');

//var path = __dirname;
var path = process.cwd();
//var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
var PollHandler = require(path + '/app/controllers/pollHandler.server.js');

module.exports = function (app, passport) {

	function isLoggedIn (req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		} else {
			res.render('login');
		}
	}

	//var clickHandler = new ClickHandler();
	var pollHandler = new PollHandler();

	app.route('/')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
				res.render('index',{poll:poll});
			})
		});

	app.route('/login')
		.get(function (req, res) {
			console.log(req.params);
			Poll.find({}, {}, { sort: { 'created_at' : -1 } }, function(err, poll) {
				console.log(poll);
			res.render('login',{poll:poll, layout:'loggedout'});
			})
		});

	/*app.route('/poll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('poll');
			})
		});*/

	app.route('/logout')
		.get(function (req, res) {
			req.logout();
			res.redirect('/login');
		});

	app.route('/profile/:id')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				console.log(user);
				res.render('profile',{user:user, time:Date.now()});
			})
		});

	app.route('/createpoll')
		.get(isLoggedIn, function (req, res) {
			console.log(req.params);
			User.findOne({"twitter.username":req.params.id}, function(err, user) {
				res.render('createpoll');
			})
		});

	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render("profile",{user:req.user});
		});

	app.route('/poll/:id')
		.get(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll.poll.choices);
				//poll.poll.choices.count++;
				res.render("poll",{poll:poll});
			})
		})
		.delete(function (req, res) {
			console.log(req.params);
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				console.log(poll);
				if (poll) {
					poll.remove();
				};
				res.render("profile",{user:req.user});
			})
		});

	app.route('/poll/:id/:choice')
		.post(function (req, res) {
			Poll.findOne({"_id":req.params.id}, function(err, poll){
				Choice.findOneAndUpdate({"_id": req.params.choice}, {$inc : {'count' : 1}});
				res.render("poll",{poll:poll});
				})
				//console.log(poll.poll.choices);
			});

	app.route('/auth/github')
		.get(passport.authenticate('github'));

	app.route('/auth/github/callback')
		.get(passport.authenticate('github', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	app.route('/auth/twitter')
		.get(passport.authenticate('twitter'));

	app.route('/auth/twitter/callback')
		.get(passport.authenticate('twitter', {
			successRedirect: '/',
			failureRedirect: '/login'
		}));

	/*app.route('/api/:id/clicks')
		.get(isLoggedIn, clickHandler.getClicks)
		.post(isLoggedIn, clickHandler.addClick)
		.delete(isLoggedIn, clickHandler.resetClicks);*/

	app.route('/createpoll')
		.post(pollHandler.addPoll);

	app.route('/success')
		.get(function (req, res) {
		//console.dir(req.body);
		res.render('success');
		});
//agasg

};
<|endoftext|>


<commit_before>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  _.bus = self
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'
  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())
    console.log(data)

    if (data.meta === 'module_map') { // add map
      map = data
      self.map = data
      self.build()
    } else if (self.scope === 'client' && data.key){
      console.log(data.key)
    } else { // pass through to out
      self.send(data)
    }
  }

  this.build = function () { // load modules && handle connections
    if (!map) throw new Error('no map')
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.forEach(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting ' + conn[key])
      console.dir(modA)
      console.dir(modB)

      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    if (self.scope==='server') _[mod.id.toUpperCase()] = require(mod.filePath)
    if (self.scope==='client') _[mod.id.toUpperCase()] = require(mod.id)

    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}

<commit_msg>removed junk from brico<commit_after>var telepath = require('tele')
, stream = require('stream')
, async = require ('async')

module.exports = function (usr) { // BRICOLEUR
  var self = this
  , map = null
  , _ = {} // module scope
  _.bus = self
  telepath(this)

  // detect if running in node or browser
  if (global.process && global.process.title === 'node') self.scope = 'server'
  if (!global.process) self.scope = 'client'
  if (usr) self.usr = usr

  this.recv = function (buffer) {
    var data = JSON.parse(buffer.toString())

    if (data.meta === 'module_map') { // add map
      map = data
      self.map = data
      self.build()
    } else { // pass through to out
      self.send(data)
    }
  }

  this.build = function () { // load modules && handle connections
    if (!map) throw new Error('no map')
    async.forEach(map[self.scope], lookupModule, connModules)

    function lookupModule (mod, cb) {
      var modules = usr.modules[self.scope]
      for (var i=0;i<modules.length;i++) {
        if (modules[i]===mod.id) {
          console.log('loading mod '+mod.id)
          self.loadModule(mod)
          break
        }
      }
      cb()
    }

    function connModules () {
      if (usr.conns) {
        console.log('modules loaded :: connecting modules...')
        async.forEach(usr.conns[self.scope], self.connModule, function () {
          console.log('connected modules for : '+usr.host)
        })
      }
      if (!usr.conns) console.log('no conns for : '+usr.host)
    }
  }

  this.connModule = function (conn, cb) { // ['modA>modB','modB>modC'] make module connections
    var modA = null
    , modB = null

    for (key in conn) { // could be clearer
      modA = _[conn[key].split('>')[0]]
      modB = _[conn[key].split('>')[1]]
      console.log('connecting ' + conn[key])

      if (!modA.out || !modB.in) throw new Error(modA+','+modB+' :no .out or .in connections')
      if (modA.out && modB.in) modA.out.pipe(modB.in)
      cb()
    }
  }

  this.disconnModule = function (disconn) {
  }

  this.loadModule = function (mod) { // load module!
    if (self.scope==='server') _[mod.id.toUpperCase()] = require(mod.filePath)
    if (self.scope==='client') _[mod.id.toUpperCase()] = require(mod.id)

    _[mod.id] = new _[mod.id.toUpperCase()]()
    if (mod.html) _[mod.id].template = mod.html
  }

  this.unloadModule = function (mod) {
  }

  // ------------------------------------------------------------
  this.addConnection = function (key) { // user socket connection
    self[key] = {}
    var s = self[key]
    s.id = key

    // add write stream
    s.in = new stream.Writable()
    s.in._write = function (chunk, encoding, cb) {
      self.recv(chunk) // add id to obj -- for filtering
      cb()
    }

    // add read stream
    s.out = new stream()
    s.out.readable = true
    s.send = function (data) {
      s.out.emit('data',JSON.stringify(data))
    }
  }

  this.removeConnection = function (key) {
    self[key].out.emit('close')
    delete self[key]
  }// ---------------------------------------------------
}
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { Helmet } from 'react-helmet';

/* eslint-disable react/no-danger */
export default function Document({
  appFavicon,
  appLocation,
  content,
  helmet,
  manifest,
  state,
  title,
  additionalContent,
  processMeta,
  processCSS,
  processJS,
}) {
  let scripts = [


<commit_before>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click' : _toggleClass,
    '[data-toggle-text]|click' : _toggleText,
    '.ls-link-smooth|click' : _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle();
  }

  function _loadEvents () {
    $.each(events, function (eventDesc,fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt){
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        textChange = $this.data('toggle-text'),
        textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll (evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if($target[0]){
      $('html,body').animate({
       scrollTop: $target.offset().top -70
      }, 1000);
    }
  }

  function _locationHashTrigger () {
    if(window.location.hash){
      $('a[class*="ls-"][href="'+window.location.hash+'"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt){
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt){
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled='disabled'];
    $elementDisabled.on('click', function(evt){
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e){
      if($(this).attr("href") === "" || $(this).attr("href") === "#"){
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle(dom_scope) {
    $(".ls-group-active .ls-btn", dom_scope).on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  return {
    init:init
  };

}());
<commit_msg>Add anchor at aside menu<commit_after>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click' : _toggleClass,
    '[data-toggle-text]|click' : _toggleText,
    '.ls-link-smooth|click' : _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle();
    menuAnchor();
  }

  function _loadEvents () {
    $.each(events, function (eventDesc,fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt){
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function menuAnchor(){
    $(".ls-active").focus().css('outline', 'none')
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        textChange = $this.data('toggle-text'),
        textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll (evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if($target[0]){
      $('html,body').animate({
       scrollTop: $target.offset().top -70
      }, 1000);
    }
  }

  function _locationHashTrigger () {
    if(window.location.hash){
      $('a[class*="ls-"][href="'+window.location.hash+'"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt){
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt){
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled='disabled'];
    $elementDisabled.on('click', function(evt){
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e){
      if($(this).attr("href") === "" || $(this).attr("href") === "#"){
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle(dom_scope) {
    $(".ls-group-active .ls-btn", dom_scope).on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  return {
    init:init
  };

}());
<|endoftext|>