Example #1
0
 getState(function(error, playerState) {
   if (error) {
     logger.error(error);
   } else {
     // Check if player stopped by itself
     if (state.properties.state === "playing" && state.properties.intendedState === "playing" && playerState === "stopped") {
       state.set("intendedState", "paused");
       state.trigger("endOfTrack");
     }
     state.set("state", playerState);
     if (playerState !== "paused" && playerState !== "stopped") {
       getTrackId(function(error, trackId) {
         if (error) {
           logger.error(error);
         } else {
           // Check if player automatically went to the next track
           if (state.properties.track.id !== trackId) {
             if (state.properties.intendedState === "playing") {
               Spotify.pause(function() {
                 state.trigger("endOfTrack");
               });
             }
           }
         }
       });
       getProgress(function(error, progress) {
         if (!error && progress !== "missing value") {
           state.set("progress", progress);
         }
       });
     }
   }
 });
Example #2
0
    it('should execute the code block wtih the right server', function() {
      var server1Count = 0, server2Count = 0;
      var proEnv = 'production', serverType1 = 'server1', serverType2 = 'server2';

      app.init({base: mockBase});
      app.set('serverType', serverType1);
      app.set('env', proEnv);

      app.configure(proEnv, serverType1, function() {
        server1Count++;
      });

      app.configure(proEnv, serverType2, function() {
        server2Count++;
      });

      app.set('serverType', serverType2);

      app.configure(proEnv, serverType1, function() {
        server1Count++;
      });

      app.configure(proEnv, serverType2, function() {
        server2Count++;
      });

      server1Count.should.equal(1);
      server2Count.should.equal(1);
    });
Example #3
0
  it('should set a session cookie', function(done) {

    config.set('api.enabled', false);
    config.set('sessions.enabled', true);
    config.set('sessions.name', 'dadiweb.sid');

    // create a page
    var name = 'test';
    var schema = help.getPageSchema();
    var page = Page(name, schema);

    page.contentType = 'application/json';
    page.template = 'session.dust';
    page.route.paths[0] = '/session';
    page.datasources = [];
    page.events = ['session'];
    delete page.route.constraint;

    startServer(page);

    var client = request(connectionString);

    client
    .get(page.route.paths[0])
    .expect(200)
    .expect('content-type', page.contentType)
    .expect(help.shouldSetCookie('dadiweb.sid'))
    .end(function (err, res) {
        if (err) return done(err);
        cleanup(done);
    });
  })
Example #4
0
SpaceFS.folderToSpace = function (path) {
  var space = new Space()
  var files = fs.readdirSync(path)
  for (var i in files) {
    var file = files[i]
    if (file === '.')
      continue
    if (file === '..')
      continue
    if (file.substr(0,1) === '.')
      continue
    var xpath = file
    var filePath = path + '/' + file
    if (file.match(/ /))
      throw "Space does not support spaces in filenames. Found a space in file: " + filePath
    var stats = fs.statSync(filePath)
    if (stats.isDirectory()) {
      space.set(xpath, SpaceFS.folderToSpace(filePath))
      continue
    }
    // If text
    if (SpaceFS.isText(file)) {
      space.set(xpath, fs.readFileSync(filePath, 'utf8'))

    }
    // Base64 encode it
    else
      space.set(xpath, fs.readFileSync(filePath).toString('base64'))
  }
  return space
}
Example #5
0
  it('should have a session object attached to the request', function(done) {

    config.set('api.enabled', false);
    config.set('sessions.enabled', true);
    config.set('sessions.name', 'dadiweb.sid');

    // create a page
    var name = 'test';
    var schema = help.getPageSchema();
    var page = Page(name, schema);

    page.contentType = 'application/json';
    page.template = 'session.dust';
    page.route.paths[0] = '/session';
    page.datasources = [];
    page.events = ['session'];
    delete page.route.constraint;

    startServer(page);

    var client = request(connectionString);

    client
    .get(page.route.paths[0])
    .expect(200)
    .expect('content-type', page.contentType)
    .end(function (err, res) {
        if (err) return done(err);

        var data = JSON.parse(JSON.stringify(res.body));
        (data.session_id !== null).should.eql(true);

        cleanup(done);
    });
  })
 before(() => {
   nocked = nock('http://www.leagueofgraphs.com');
   nocked_riot = nock('http://ddragon.leagueoflegends.com');
   store.set('riot_ver', '6.6.1');
   store.set('leagueofgraphs_ver', '6.6');
   store.set('champs', ['ahri']);
 });
Example #7
0
        it('should accept database connection as third argument', function (done) {

            config.set('database.enableCollectionDatabases', true);
            connection.resetConnections()
            var conn = connection({
                "username": "",
                "password": "",
                "database": "test",
                "replicaSet": "",
                "hosts": [
                    {
                        "host": "localhost",
                        "port": 27020
                    }
                ]
            });

            var mod = model('testModelName', help.getModelSchema(), conn)
            should.exist(mod.connection);
            mod.connection.connectionOptions.hosts[0].host.should.equal('localhost');
            mod.connection.connectionOptions.hosts[0].port.should.equal(27020);
            mod.connection.connectionOptions.database.should.equal('test');

            config.set('database.enableCollectionDatabases', false);

            done();
        });
Example #8
0
    it('should execute the code block wtih the right environment', function() {
      var proCount = 0, devCount = 0;
      var proEnv = 'production', devEnv = 'development', serverType = 'server';

      app.init({base: mockBase});
      app.set('serverType', serverType);
      app.set('env', proEnv);

      app.configure(proEnv, serverType, function() {
        proCount++;
      });

      app.configure(devEnv, serverType, function() {
        devCount++;
      });

      app.set('env', devEnv);

      app.configure(proEnv, serverType, function() {
        proCount++;
      });

      app.configure(devEnv, serverType, function() {
        devCount++;
      });

      proCount.should.equal(1);
      devCount.should.equal(1);
    });
Example #9
0
    it('should run globalEvents within the get request', function(done) {
      config.set('api.enabled', false);
      config.set('allowJsonView', true);
      config.set('globalEvents', ['test_global_event'])

      var page = getPage();
      startServer(page);

      // provide API response
      var apiResults = { results: [{_id: 1, title: 'books'}] }
      sinon.stub(help.DataHelper.prototype, 'load').yields(null, apiResults);

      // provide event response
      var results = { results: [{_id: 1, title: 'books'}] }
      var method = sinon.spy(Controller.Controller.prototype, 'loadEventData');

      var client = request(connectionString);

      client
      .get(page.route.paths[0] + '?json=true')
      //.expect(200)
      .end(function (err, res) {
        if (err) return done(err);
        method.called.should.eql(true);
        method.firstCall.args[0].should.eql(controller.preloadEvents);
        method.restore()
        help.DataHelper.prototype.load.restore();

        res.body['global_event'].should.eql('FIRED');

        cleanup(done);
      });
    })
Example #10
0
 it("should store two Date objects distinctively", function () {
     map.set(date1, "date 1");
     map.set(date2, "date 2");
     assert.strictEqual(map.get(date1), "date 1");
     assert.strictEqual(map.get(date2), "date 2");
     assert.ok(!map.has(new Date()));
     assert.ok(!map.has(new Date()));
 });
Example #11
0
    it('should use an in-memory store if none is specified', function(done) {
      config.set('sessions.enabled', true);
      config.set('sessions.store', '');

      (Server.getSessionStore(config.get('sessions')) === null).should.eql(true);

      done();
    });
Example #12
0
    it('should use specified database when creating a connection', function (done) {

      var dbConfig = {
            "hosts": [
                {
                    "host": "127.0.0.1",
                    "port": 27017
                }
            ],
            "username": "",
            "password": "",
            "database": "test",
            "ssl": false,
            "replicaSet": "",
            "enableCollectionDatabases": false,
            "secondary": {
                "hosts": [
                    {
                        "host": "127.0.0.1",
                        "port": 27017
                    }
                ],
                "username": "",
                "password": "",
                "replicaSet": "",
                "ssl": false
            }
      }

      var auth = {
          "tokenUrl": "/token",
          "tokenTtl": 1800,
          "database": {
              "hosts": [
                  {
                      "host": "127.0.0.1",
                      "port": 27017
                  }
              ],
              "username": "",
              "password": "",
              "database": "separate_auth_db"
          },
          "clientCollection": "clientStore",
          "tokenCollection": "tokenStore"
      }

      var oldConfig = config.get('auth');
      config.set('auth', auth);

      var store = tokenStore();

      should.exist(store.connection);
      store.connection.connectionOptions.database.should.equal('separate_auth_db');

      config.set('auth', oldConfig);
      done();
    });
    it('shouldn\'t throw an error if called more than once when the initial call had freeze set to false', () => {
        const config = require(pathToReactGlobalConfiguration);

        const configuration = { baz: 'qux' };
        config.set({ foo: 'bar' }, { freeze: false });
        config.set(configuration);

        config.get().should.deep.equal(configuration);
    });
Example #14
0
  it('should use specified database when creating a connection', function (done) {
    var dbConfig = {
      'hosts': [
        {
          'host': '127.0.0.1',
          'port': 27017
        }
      ],
      'username': '',
      'password': '',
      'database': 'test',
      'ssl': false,
      'replicaSet': '',
      'enableCollectionDatabases': false,
      'secondary': {
        'hosts': [
          {
            'host': '127.0.0.1',
            'port': 27017
          }
        ],
        'username': '',
        'password': '',
        'replicaSet': '',
        'ssl': false
      }
    }

    var auth = {
      'tokenUrl': '/token',
      'tokenTtl': 1800,
      'database': {
        'hosts': [
          {
            'host': '127.0.0.1',
            'port': 27017
          }
        ],
        'username': '',
        'password': '',
        'database': 'separate_auth_db'
      },
      'clientCollection': 'clientStore',
      'tokenCollection': 'tokenStore'
    }

    var oldConfig = config.get('auth')
    config.set('auth', auth)

    var store = tokenStore()

    should.exist(store.connection)
    store.connection.connectionOptions.database.should.equal('separate_auth_db')

    config.set('auth', oldConfig)
    done()
  })
    it('should extend the configuration, rather than replacing them if assign is set to true', () => {
        const config = require(pathToReactGlobalConfiguration);

        config.set({ foo: 'bar' }, { freeze: false });
        config.set({ baz: 'qux' }, { assign: true });
        config.get().should.deep.equal({ foo: 'bar', baz: 'qux' });
        config.set({ foo: { bar: 'baz' } }, { assign: true });
        config.get().should.deep.equal({ foo: { bar: 'baz' }, baz: 'qux' });
    });
Example #16
0
    it('should load globalEvents in the controller instance', function(done) {
      config.set('api.enabled', false);
      config.set('globalEvents', ['test_global_event'])

      var page = getPage();
      controller = Controller(page, options);
      controller.preloadEvents.should.exist;
      controller.preloadEvents[0].name.should.eql('test_global_event');
      done();
    })
Example #17
0
File: log.js Project: PoeBlu/api
 it('should use bunyan log.trace when log.trace is called', function (done) {
   config.set('logging.level', 'trace');
   var message = 'Hello';
   var logger = log.get();
   var method = sinon.spy(logger, 'trace');
   log.trace(message);
   logger.trace.restore();
   method.called.should.eql(true);
   config.set('logging.level', 'info');
   done();
 });
Example #18
0
		serverHelpers.getNetworkIPs(function(err, ips) {
			if(err || !ips.length) {
				config.set('IP', 'localhost');
				console.log('   * * * * * * * * * * * *   Civic Seed:'.yellow + ' could not find network ip. Defaulting to \'localhost.\'\n\n'.red);
			} else {
				config.set('IP', ips[0]);
				console.log('   * * * * * * * * * * * *   Civic Seed:'.yellow + ' running on network ip: ' + ips[0].yellow + '\n\n');
			}
			if(typeof callback === 'function') {
				callback();
			}
		});
	it("should bind shortcut", () => {

		assert.strictEqual(
			Conf.set("test", "test").shortcut("test", "t") instanceof NodeConfManager, true,
			"return data is not an instanceof NodeConfManager"
		);

		assert.strictEqual(
			Conf.set("test", "test").shortcut("TEST", "T") instanceof NodeConfManager, true,
			"return data is not an instanceof NodeConfManager"
		);

	});
    function _save(path) {
        var db = require(STORAGE_MODULE_NAME),
            mod = Cache[path];

        db && (mod.factory ?
            db.set(MODULE_CACHE_KEY, {
                path: path,
                factory: mod.factory.toString(),
                deps: JSON.stringify(mod.deps)
            }) : db.set(MODULE_CACHE_KEY, {
                path: path,
                json: JSON.stringify(mod.json)
            }));
    }
Example #21
0
  it('should use main config api settings if no port specified', function(done) {
    var name = 'test';
    var schema = help.getPageSchema();
    var dsName = 'car-makes';

    config.set('api.host', 'api.example.com');
    config.set('api.port', 80);

    var ds = datasource(name, dsName, help.getPathOptions(), function() {});
    delete ds.schema.datasource.source.port;
    ds.buildEndpoint(ds.schema, function() {});
    ds.endpoint.should.eql('http://127.0.0.1:80/1.0/cars/makes?count=20&page=1&filter={}&fields={"name":1,"_id":0}&sort={"name":1}');
    done();
  });
Example #22
0
var componentModule = function (required) {
  var express = required.express;
  var users_component = express();
  var path = required.path;
  var util = required.util;

  //MODEL DATA
  var users = (function () {
    var data = [{'name': 'Keith'},
      {'name': 'Jason'},
      {'name': 'Phil'},
      {'name': 'Patrick'},
      {'name': 'Wes'}
    ];

    return {
      findAll: function () {
        return data;
      },
      find: function (id) {
        return data[id - 1];
      }
    }
  }());

  //CHILD-APP DIRECTORIES
  var controllerDir = path.join(__dirname, '/controller');
  var viewDir = path.join(__dirname, '/view');

  //REQUIRE SERVICES
  var controller = require(controllerDir);
  var view = require(viewDir);

  //SETUP STATIC PAGES ON CHILD-APPS
  view.use(express.static(viewDir));
  controller.use(express.static(controllerDir));

  //INJECT THE MODEL INTO THE CONTROLLER
  controller.set('model', users);

  //INJECT THE CONTROLLER INTO THE VIEW
  view.set('controller', controller);

  //SETUP THE SERVICES AS ROUTES
  users_component.use('/users', view);
  view.use('/controller', controller);

  return users_component;
};
Example #23
0
        it('should set a config key to the passed value', function() {

            cg = new Config({
                path: configPath + configFile
            });

            cg.set('propOne', 'wohoo');
            cg.set('fancy', ['orly']);

            var result1 = cg.get('propOne');
            var result2 = cg.get('fancy');

            result1.should.equal('wohoo');
            result2.should.eql(['orly']);
        });
Example #24
0
    it('should run events in the order they are specified', function(done) {
      config.set('allowJsonView', true);
      var page = getPage();
      page.events = ['b','a']

      startServer(page);

      // provide API response
      var apiResults = { results: [{_id: 1, title: 'books'}] }
      sinon.stub(help.DataHelper.prototype, 'load').yields(null, apiResults);

      // provide event response
      var method = sinon.spy(Controller.Controller.prototype, 'loadEventData');

      var client = request(connectionString);

      client
      .get(page.route.paths[0] + '?json=true')
      //.expect(200)
      .end(function (err, res) {
        if (err) return done(err);

        method.called.should.eql(true);
        method.secondCall.args[0][0].should.eql(controller.events[0])
        method.restore()
        help.DataHelper.prototype.load.restore();

        res.body['b'].should.eql('I came from B');
        res.body['a'].should.eql('Results for B found: true');

        cleanup(done);
      });
    })
Example #25
0
                'delete path, when last glob removed' : () => {
                    path.set('src', '<root>/src');

                    path.removeFrom('src', '<root>/src');

                    assert.deepStrictEqual(path.getAll(), {});
                },
function main() {
  if (app.get('loopback-component-auto-migrate-status')){
    console.log('loopback-component-auto-migrate is already enabled in "server/model-config.json"')
    return;
  }
  var parseArgs = require('minimist');
  var info;
  var opts = {
    boolean: ['update', 'data', 'import'],
    alias: {'update':'u', 'data':'d', 'import':'i'},
    default:{'update': false, 'data': true}
  };
  var argv = parseArgs(process.argv.slice(2), opts);
  var folder = argv._.pop();
  var result;
  app.set('migrating', true)
  if (argv.import) {
    if (!folder) folder = defaultFolder;
    console.log('import data only:', folder);
    result = autoLoadData(app, {fixtures:folder})
    if (folder) result = result.then(function(){return createDefaults()})
    result.then(function(){
      console.log('import successful.')
    })
    .error(function(err){
      console.log('import failed:', err.message)
    })
  } else {
    if (argv.data && !folder) folder = defaultFolder;
    info = 'Migrate database';
    if (folder) info += ': ' + folder;
    console.log(info)
    migrate(folder, !argv.update);
  }
  // argv
  // .version('v0.1.0')
  // .info('Migrate the database and data.')
  // .option({
  //   name: 'update',
  //   short: 'u',
  //   type: 'boolean',
  //   description: 'update database only, defaults to false'
  // })
  // .option({
  //   name: 'load',
  //   short: 'l',
  //   type: 'boolean',
  //   description: 'load data'
  // })
  // ;
  // var args = argv.run();
  // var folder = argv.targets.pop()
  // console.log(args);
  // if (args.options.load) {

  // } else {
  //   if (args.options.update !== undefined) args.options.update = !args.options.update;
  //   migrate(folder, args.options.update);
  // }
}
    it('should enable context with loopback.rest', function(done) {
      app.enableAuth({ dataSource: 'db' });
      app.set('remoting', { context: { enableHttpContext: true }});
      app.use(loopback.rest());

      invokeGetToken(done);
    });
 it('should report 404 for disabled legacy explorer route /models', function(done) {
   app.set('legacyExplorer', false);
   app.use(loopback.rest());
   request(app).get('/models')
     .expect(404)
     .end(done);
 });
Example #29
0
    it('should play the role of normal set and get', function() {
      should.not.exist(app.get('some undefined key'));

      var key = 'some defined key', value = 'some value';
      app.set(key, value);
      value.should.equal(app.get(key));
    });
Example #30
0
      .end(function (err, res) {
        if (err) return done(err);

        config.set('rewrites.datasource', '')

        done()
      })