Ejemplo n.º 1
0
function getAll(req,res) {
    bluebird.coroutine(function *() {
        console.log(1);
        let tasks = yield model.Task.find()
            .select('description _id').exec();
        console.log(2);
        res.json(tasks);
        console.log(3);
    })()
        .catch(function(err) {
            console.log(err);
            res.sendStatus(404);
        });
}
Ejemplo n.º 2
0
function getById(req, res) {
    var taskId = req.params.taskId;
    bluebird.coroutine(function *() {
        let task = yield model.Task.findById(taskId)
            .select('description _id')
            .exec();
        res.json({
            task: task
        });
    })()
        .catch(function () {
            res.sendStatus(400);    
        });
}
Ejemplo n.º 3
0
function deleteById(req,res) {
    console.log("del req");
    var taskId = req.params.taskId;
    console.log(taskId);
    bluebird.coroutine(function * () {
        yield model.Task.findById(taskId).remove().exec();
        console.log("deleted task with taskId: " + taskId);
        res.end();
    })()
        .catch(function(){
            console.log("couldn't find task id:" + taskId);
            res.sendStatus(400);
        });
}
Ejemplo n.º 4
0
module.exports = function(properties) {
    properties.onEvent(co(function*(event, data) {
        if (event === "propertyChange") {
//             console.log(JSON.stringify(data, null, 2));
            if (data.unitId === "keyboard" && data.data.name === "Data") {
                if (data.data.newValue === "KEY_F1") {
                    yield properties.set("yamahareceiver", "Power", true);
                    yield properties.set("livingroom-tv", "Power", true);

                    if (properties.get("yamahareceiver", "Source") === "HDMI1") {
                        properties.set("yamahareceiver", "Source", "AV1");
                        properties.set("livingroom-tv", "Source", "DTV");
                    } else {
                        properties.set("yamahareceiver", "Source", "HDMI1");
                        properties.set("livingroom-tv", "Source", "HDMI2");
                    }
                } else if (data.data.newValue === "KEY_F2") {
                    properties.set("livingroom-ceiling", "Value", 255);
                    properties.set("livingroom-ceiling", "Value", 255);
                    properties.set("livingroom-vitrine", "Value", 255);
                    properties.set("livingroom-window", "Value", 255);
                    properties.set("livingroom-bar", "Value", 255);
                    properties.set("hall-ceiling", "Value", 255);
                    properties.set("hall-mirror", "Value", 255);
                    properties.set("bedroom-wall", "Value", 255);
                    properties.set("bedroom-ceiling", "Value", 255);
                    properties.set("bedroom-door", "Value", 255);
                } else if (data.data.newValue === "KEY_F3") {
                    properties.set("yamahareceiver", "Power", false);
                    properties.set("livingroom-tv", "Power", false);
                    properties.set("livingroom-ceiling", "Value", 0);
                    properties.set("livingroom-window", "Value", 0);
                    properties.set("livingroom-vitrine", "Value", 0);
                    properties.set("livingroom-bar", "Value", 0);
                    properties.set("hall-ceiling", "Value", 0);
                    properties.set("hall-mirror", "Value", 0);
                    properties.set("bedroom-wall", "Value", 0);
                    properties.set("bedroom-ceiling", "Value", 0);
                    properties.set("bedroom-door", "Value", 0);
                }
            } else if (data.unitId === "nexa-remote" && data.data.newValue.payload.protocol === "arctech") {
                let id = data.data.newValue.payload.group + "_" + data.data.newValue.payload.unit;

                if (id === "0_1") {
                    properties.set("livingroom-ceiling", "Value", data.data.newValue.payload.method === "turnon" ? 255 : 0);
                }
            }
        }
    }));
};
Ejemplo n.º 5
0
function updateDescription(req,res) {
    console.log("update request");
    var taskId = req.params.taskId;
    var description = req.body.description;
    bluebird.coroutine(function * () {
        yield model.Task.findById(taskId).update({"description":description}).exec();
        console.log("updated successfully with desc:" + description);
        res.sendStatus(200);
    })()
        .catch(function () {
            console.log("unable to update:"+description);
            res.statusCode(400);
        });
}
Ejemplo n.º 6
0
 static findById(id, done) {
   bluebird.coroutine(function *() {
     try {
       const users = yield makeQuery('SELECT * FROM users WHERE id = $1',
           [id]);
       if (users.length > 0) {
         return done(null, users[0]);
       }
     } catch (err) {
       console.error(err);
       return done(err, null);
     }
   })();
 }
Ejemplo n.º 7
0
 ircRooms.forEach(function(room) {
     if (room.server.claimsUserId(user.getId())) {
         req.log.info("%s is a virtual user (claimed by %s)",
             user.getId(), room.server.domain);
         return;
     }
     // get the virtual IRC user for this user
     promises.push(Promise.coroutine(function*() {
         let bridgedClient = yield self.ircBridge.getBridgedClient(
             room.server, user.getId(), (event.content || {}).displayname
         );
         yield bridgedClient.joinChannel(room.channel); // join each channel
     })());
 });
function getProgress(query) {
    var jiraOpts = utils.loadConfig().jira;

    var jira = new JiraApi(
        jiraOpts.protocol, jiraOpts.host, jiraOpts.port,
        jiraOpts.userName, jiraOpts.password, jiraOpts.apiVersion, jiraOpts.verbose);

    var searchOptions = {
        maxResults: jiraOpts.maxIssueResults,
        fields: ['timeoriginalestimate', 'timeestimate', 'timespent', 'summary']
    };


    //var query = `project = "${jiraOpts.projectKey}" and updatedDate >= "${srchStartDate}" order by updatedDate desc `;
    var searchPromise = Promise.promisify(jira.searchJira.bind(jira));

    logger.info('jira query: ' + query);

    var getResult = Promise.coroutine(function *() {
        var data = yield searchPromise(query, searchOptions);
        return data;
    });

    return getResult().then((result) => {
        const getEstimation = (it) => ( +(it.fields.timeoriginalestimate) || +(it.fields.timeestimate) || 0);
        const getSpent = (it) => ( +(it.fields.timespent ) || 0);
        const timeSpentSummary = _.reduce(result.issues, (sum, it) => {
            return sum + getSpent(it);
        }, 0);
        const timeEstimatedSummary = _.reduce(result.issues, (sum, it) => {
            return sum + getEstimation(it);
        }, 0);
        console.log('timespent summary', timeSpentSummary);
        console.log('timeEstimated summary', timeEstimatedSummary);
        console.log('progress ', (timeSpentSummary / timeEstimatedSummary).toFixed(2) * 100, '%');
        console.log(`validation failed for:`);
        let invalidCount = 0;
        result.issues.forEach(it => {
            if (getEstimation(it) <= getSpent(it)) {
                console.log(`${it.key} : ${it.fields.summary}`, getEstimation(it), getSpent(it));
                invalidCount++;
            }
        });

        console.log(`invalid ${invalidCount} or ${result.issues.length}`);
        return result;
    });

}
    it("should load cluster definition and display merged content, keeping initial values", done => {
      return Promise.coroutine(function*() {
        const clusterDefs = yield yamlHandler.loadClusterDefinitions(
          "./test/fixture/clusters"
        );
        expect(clusterDefs).to.exist;
        expect(clusterDefs.length).to.equal(4);

        // Load Cluster Def
        const clusterDef = clusterDefs[3];
        expect(clusterDef).to.exist;
        expect(clusterDef.name()).to.equal("test-fixture");
        expect(clusterDef.server).to.equal(
          "https://test-fixture.k8s-controller.example.com"
        );
        expect(clusterDef.rsConfig.deployment).to.exist;
        expect(clusterDef.rsConfig.deployment.replicaCount).to.equal(2);
        expect(clusterDef.rsConfig.deployment.imagePullPolicy).to.not.exist;

        // Load the base definitions
        const baseDef = yield yamlHandler.loadBaseDefinitions("./test/fixture");
        expect(baseDef).to.exist;
        const authBase = baseDef.resource("auth");
        expect(authBase).to.exist;
        expect(authBase.containers["auth-con"].env.length).to.equal(1);
        expect(authBase.containers["auth-con"].env).to.include({
          name: "test",
          value: "testbase"
        });

        // Merge content
        clusterDef.apply(baseDef);
        // Should have combined data
        expect(clusterDef.rsConfig.deployment.imagePullPolicy).to.equal(
          "IfNotPresent"
        );
        expect(clusterDef.rsConfig.deployment.containerPort).to.equal(80);
        const authResource = clusterDef.resource("auth");
        expect(authResource).to.exist;
        expect(authResource.containers["auth-con"].env.length).to.equal(1);
        expect(authResource.containers["auth-con"].env).to.include({
          name: "test",
          value: "testvalue"
        });
        done();
      })().catch(err => {
        done(err);
      });
    });
Ejemplo n.º 10
0
 .then(() => {
     var fn_to_check = [
         {
             action: "nonexistent",
             params: ["who does care at all?"],
             id: "0"
         },
         {
             action: "getMulti",
             params: [["operator/1", "operator/2"]],
             id: "1"
         },
         {
             action: "remove",
             params: ["something/1"],
             id: "10"
         },
         {
             action: "insert",
             params: ["something/1", 42],
             id: "11"
         },
         {
             action: "upsert",
             params: ["something/1", 24],
             id: "100"
         },
         {
             action: "get",
             params: ["something/1"],
             id: "101"
         }
     ];
     var check = Promise.coroutine(function* () {
         for (var i in fn_to_check) {
             var evdata = fn_to_check[i];
             console.log("Emitting request with data :", evdata);
             yield Promise.delay(1000);
             ee.addTask('dbface.request', evdata)
                 .then((res) => {
                     console.log("RES", res);
                 })
                 .catch((err) => {
                     console.log("ERR", err.message)
                 });
         }
     });
     check();
 });
Ejemplo n.º 11
0
router.put('/:id',passport.authenticate('jwt', { session: false }),(req, res) => {
  const id = req.param('id');
  Log.debug(id);
  const updated = req.body;
  Promise.coroutine(function* () {
    const userProfile = yield req.user.getProfile();
    Log.debug(userProfile.id);
    if (id == userProfile.id) {
      yield userProfile.update(updated);
      res.json({message: 'Success'});
    } else {
      res.status(403).json({success: false, msg: 'Wrong profile!'});
    }
  })().catch(err => Log.error(err));
});
Ejemplo n.º 12
0
 describe("markTodo", function() {
   beforeEach(() => 
     db.addTodo('aUser', 'hi', 0)
   )
   it("should check an unchecked item", Promise.coroutine(function*() {
     yield db.markTodo('aUser', 0)
     
     expect(yield db.listTodos('aUser')).to.deep.equal([{text: 'hi', checked: true, id: 0}])
   }))
       
   it("should uncheck a checked item", Promise.coroutine(function*() {
     yield db.markTodo('aUser', 0)
     yield db.markTodo('aUser', 0)
     
     expect(yield db.listTodos('aUser')).to.deep.equal([{text: 'hi', checked: false, id: 0}])
   }))
   
   it("shouldn't touch other items", Promise.coroutine(function*() {
     yield db.addTodo('aUser', 'bye', 1)
     yield db.markTodo('aUser', 1)
     
     expect(yield db.listTodos('aUser')).to.deep.equal([{text: 'hi', id: 0}, {text: 'bye', checked: true, id: 1}])
   }))
 })
Ejemplo n.º 13
0
    app[routeMethodName] = function () {
      const args = _.toArray(arguments);
      const originalRouteHandler = _.last(args);

      if (isGenerator(originalRouteHandler)) {
        const routeHandler = Promise.coroutine(originalRouteHandler);

        // Overwrite the route handler.
        args[args.length - 1] = function (req, res, next) {
          routeHandler(req, res, next).catch(next);
        };
      }

      return originalRouteMethod.apply(this, args);
    };
    it('should create a new glyph with its coordinates and data', function(done) {
      var createGlyphTest = Promise.coroutine(function*() {
        // createGlyph returns the documentid of the created glyph
        var createGlyphResult = yield createGlyph(25, 25, {name: "yolo"});
        var GISResult = yield GIS.select('*').from('locations').where({glyphid: createGlyphResult});
        // need to convert id from string to ObjectID type for mongo to understand
        var docStoreResult = yield docStore.glyphData.find({_id: new ObjectID(createGlyphResult)});

        GISResult[0].glyphid.should.equal(createGlyphResult);
        docStoreResult[0].name.should.equal('yolo');

        done();
      });
      createGlyphTest();
    });
Ejemplo n.º 15
0
var Foo = (function () {
  function Foo() {}

  _prototypeProperties(Foo, null, {
    foo: {
      value: _bluebird.coroutine(function* () {
        var wat = yield bar();
      }),
      writable: true,
      configurable: true
    }
  });

  return Foo;
})();
Ejemplo n.º 16
0
// find an edge what's partially on the graph, and partially off the graph
function findEdgeToExpand(sg, edges) {
  return bluebird.coroutine(function*() {
    let selected = null;

    for(let edge of edges) {
      // since the edges are sorted by pref, we can exit early
      if(selected && edge.options.pref < selected.edge.options.pref)
        return selected;

      selected = yield exports.units.updateSelected(sg, edge, selected);
    }

    return selected;
  })();
}
Ejemplo n.º 17
0
    it('area player create/connect/join/quit/remove/getPlayers test', function(cb){
        var app = env.createApp('area-server-1', 'area');
        P.coroutine(function*(){
            yield P.promisify(app.start, app)();

            var areaController = app.controllers.area;
            var playerController = app.controllers.player;
            yield app.memdb.goose.transaction(P.coroutine(function*(){
                var playerId = yield playerController.createAsync({
                    authInfo: {socialId : '123', socialType: consts.binding.types.DEVICE},
                    name : 'rain'
                });
                var areaId = yield areaController.searchAndJoinAsync(playerId, {name : 'area1'});
                console.log('searchAndJoinAsync return: %j', areaId);
                areaId = areaId.data.area.id;
                var players = yield areaController.getPlayersAsync(areaId);
                players.length.should.eql(1);
                players[0]._id.should.eql(playerId);

                yield playerController.connectAsync(playerId, 'c1');
                yield areaController.pushAsync(areaId, null, 'chat', 'hello', true);
                var msgs = yield areaController.getMsgsAsync(areaId, 0);
                msgs.length.should.eql(1);
                msgs[0].msg.should.eql('hello');

                var playerId1 = yield playerController.createAsync({
                    authInfo: {socialId : '1234', socialType: consts.binding.types.DEVICE},
                    name : 'rain1'
                });
                yield areaController.joinAsync(areaId, playerId1);

                yield areaController.disconnectAsync(playerId1, areaId);

                var area = yield app.models.Area.findById(areaId);
                area.playerIds.toObject().should.eql([playerId, null]);

                yield areaController.quitAsync(areaId, playerId);
                yield playerController.removeAsync(playerId);

                should.not.exist(yield app.models.Area.findById(areaId));

                app.timer.clearAll();
            }), app.getServerId());

            yield P.promisify(app.stop, app)();
        })()
        .nodeify(cb);
    });
Ejemplo n.º 18
0
  findBySlug: (productSlug,brand) => {

    return bluebird.coroutine(function* (){
      var brandModel;
      if(!_.isEmpty(brand)) {
        var Brand = mongoose.model('brand')
        brandModel = yield Brand.findOne({'slug':brand})
      }
      var Product = mongoose.model('product')
      var q = {
        status:1,
        active:true,
        slug:productSlug
      }
      if(!_.isEmpty(brandModel)) {
        q['brandID'] = mongoose.Types.ObjectId(brandModel.id)
      }
      var p = yield Product
        .findOne(q)
        .populate('brandID')
        .populate('cheapestPrice.affiliateID')
        .populate('price.affiliateID')
        .populate('cheapestPrice.affiliateProductID')
        .populate('price.affiliateProductID')
      var newPrice = []
      _.forEach(p.toJSON().price, function(price) {
        price.affiliate = price.affiliateID
        price.affiliateProduct = price.affiliateProductID
        newPrice.push(price)
      })
      var returnProduct = p.toJSON()
      returnProduct.price = newPrice
      returnProduct.cheapestPrice['affiliate'] = p.cheapestPrice.affiliateID
      returnProduct.cheapestPrice['affiliateProduct'] = p.cheapestPrice.affiliateProductID
      var currentRate = {}
      if(!_.isEmpty(returnProduct.cheapestPrice.exchangerates)) {
        var exchangeRates = returnProduct.cheapestPrice.exchangerates

        _.forEach(exchangeRates, function(c) {
          if(c.currency == 'SGD') {
            currentRate = c
          }
        })
      }
      returnProduct.cheapestPrice.exchangerates = currentRate
      return returnProduct
    })()
  },
Ejemplo n.º 19
0
				start: () => {
					if (fs.existsSync(fd.jsonFile) && fs.existsSync(fd.jarFile)) {
						if (fs.existsSync(fd.lockFile)) {
							console.info(`Minecraft [${version}] version exist.`);
							return TaskEvent.emit('done');
						}
						fs.unlinkSync(fd.jsonFile);
						fs.unlinkSync(fd.jarFile);
					}

					var start = Promise.coroutine(function*() {
						try {

							//  从manifest中获取version json文件
							const versions = Manifest.formatedVersions();
							const currentversion = versions[version];
							if (currentversion === undefined) {
								return TaskEvent.emit('error', `Can not find [${version}] from mojang server.`);
							}

							// 创建version文件夹
							if (!fs.existsSync(`${fd.version}`)) {
								IO.createFolders(`${fd.version}`);
								console.info(`created ${fd.version} folder.`);
							}

							// 下载并存储 version json
							console.info(`downloading Minecraft [${version}] version json file. ${currentversion.json}`);
							TaskEvent.emit('json');
							var versionContent = yield IO.request(currentversion.json);
							yield IO.writeFile(fd.jsonFile, versionContent);

							// 下载并存储 client jar
							const clientUrl = Url.getClientUrl(version);
							console.info('downloading client jar: %s', clientUrl);
							const DownloadProcess = IO.downloadFileToDisk(clientUrl, fd.jarFile, 10);
							DownloadProcess.on('process', (process) => TaskEvent.emit('process', process));
							DownloadProcess.on('done', () => {
								fs.writeFileSync(fd.lockFile, '');
								TaskEvent.emit('done');
							});
							DownloadProcess.on('error', (err) => TaskEvent.emit('error', err));
						} catch (e) {
							TaskEvent.emit('error', e);
						}
					});
					start();
				}
Ejemplo n.º 20
0
  /**
	 * Example path for loading env configuration files:
	 *   /auth/cluster-env.yaml
	 *
	 * Requires a env called CONFIGURATION_PATH set with the base path to load
	 * the env files from.
	 *
	 * @param  {[type]} service     resource object (must have at least { service.name } property)
	 * @param  {[type]} cluster     name of cluster
	 * @return {[type]}             ENV values
	 */
  fetch(service, cluster) {
    return Promise.coroutine(function*() {
      if (!service.name || !cluster) {
        throw new Error("Missing argument, all values are required.");
      }

      let file = path.join(
        this.configPath,
        service.name,
        `${cluster.name()}-env.json`
      );
      const data = yield readFilePromise(file, "utf8");
      let config = JSON.parse(data);
      return config;
    }).bind(this)();
  }
Ejemplo n.º 21
0
  pushStory(story, index) {
    return BPromise.coroutine(function* () {
      var msg = (!R.isNil(index)) ? "    " + ((Number(index) + 1) + " ") : "  ";
      msg += "Push to project " + chalk.green(story.project_id) + " story ";
      msg += chalk.green(story.name);
      utils.log(msg);

      story = yield this.client.createStoryAsync(story.project_id, story);

      if (story.kind === 'error') {
        console.log('story:', story);
      }

      return story;
    }.bind(this))();
  }
        this.coroutines.findResource.main = Promise.coroutine(function* (req, res, next, config) {

            let query, q, maxdist = parseFloat(req.query.radius || 2000) / 6371,
                limit = Math.min(Math.max(parseInt(req.query.limit || 10000), 0), 10000),
                sort = req.query.sort || {"updated": -1},
                skip = Math.max(parseInt(req.query.skip || 0), 0),
                uuid = req.params.region_uuid || req.params.uuid,
                region = yield mongoose.model("Region").findOne({$or: [{uuid: uuid}, {slug: uuid}]}),
                isAdmin = req.api_key &&  req.api_key.scopes && (
                        req.api_key.scopes.indexOf("admin") > -1 ||
                        req.api_key.scopes.indexOf("region-" + region.uuid) > -1
                    );

            if ((!isAdmin && !region && !config.query.user_mapping) || (!isAdmin && region.hide)) {
                return rHandler.handleErrorResponse(new restifyErrors.NotFoundError(), res, next);
            }

            query = require('../lib/util/query-mapping')({}, req, config);
            query = conditionalAdd(query, "hidden", false, !isAdmin);
            query = conditionalAdd(query, "region_uuid", region ? region.uuid : undefined);
            query = conditionalAdd(query, "lonlat", {
                $near: [parseFloat(req.query.longitude || 10.0014), parseFloat(req.query.latitude || 53.5653)],
                $maxDistance: maxdist
            }, (req.query.longitude !== undefined && req.query.latitude !== undefined));

            q = mongoose.model("Location").find(query);
            q = q.sort(sort);
            q = q.select("uuid updated hidden title");
            q = q.skip(skip).limit(limit);

            var data = { page: Math.floor(skip / limit), pagesize: limit };
            data.results = yield q.exec();
            data.total = yield mongoose.model("Location").count(q._conditions);

            data.results = yield Promise.map(data.results, Promise.coroutine(function* (result) {
                result = result.toObject();
                result.comments = yield mongoose.model(config.resource).find({subject_uuid: result.uuid})
                    .select(config.select).exec();
                result.comments = result.comments ? result.comments : undefined;
                result.commentCount = result.comments.length;
                return result;
            }));

            data.results = data.results.filter(function(item){ return item.commentCount > 0; });

            rHandler.handleDataResponse(data, 200, res, next);
        });
Ejemplo n.º 23
0
/**
 * dockerCommand() returns a function that takes 2 parameters
 * based on the passed in command object, which represents a task to perform in the command line
 *
 * @param {Object} cmd
 * @return {Function} returns a function that takes 2 parameters
 */
function dockerCommand(cmd) {
  return co(function *g(machineName, arg) {
    let error;
    try {
      const config = yield machine.machineConfig(machineName);
      config.uri += cmd.uri(arg);
      config.method = cmd.method;
      config.json = true;
      error = cmd.error;
      if (cmd.cmd === 'create') config.body = arg;
      return yield rp(config);
    } catch (e) {
      // if (e === FAILED_TO_ACCESS_MACHINE) throw FAILED_TO_ACCESS_MACHINE;
      throw e;
    }
  });
}
Ejemplo n.º 24
0
exp.login = function(userId, time) {

  return onebyone.addAsync(P.coroutine(function*(cb) {

    let remainInfo = yield exp.queryActiveCountInfo(time);
    let offset = userId - consts.USER_ID_BEGIN;
    if (remainInfo.active.get(offset)) {
      return cb();
    }
    remainInfo.active.set(offset, true);

    let sql = `UPDATE ${STATISTIC_DB_NAME}.activeCount SET active = ? WHERE date = ?`;
    let sqlArgs = [remainInfo.active.dehydrate(), remainInfo.date];
    yield mysqlUtil.query(sql, sqlArgs);
    cb();
  }))
}
Ejemplo n.º 25
0
  constructor(fn) {
    super();

    console.assert(isFunction(fn), 'should be function');

    let name = fn.name;
    if (name) {
      name = decamelize(name, '-');
      if (name.startsWith('exhibit-')) name = name.substring(8);
    }
    else name = '[anonymous]';

    Object.defineProperties(this, {
      fn: {value: isGeneratorFunction(fn) ? coroutine(fn) : fn},
      name: {value: name},
    });
  }
Ejemplo n.º 26
0
 static findOrCreate(profile, done) {
   bluebird.coroutine(function *() {
     try {
       let users = yield makeQuery('SELECT * FROM users WHERE id = $1',
           [profile.id]);
       if (users.length > 0) {
         return done(null, users[0]);
       }
       users = yield makeQuery('INSERT INTO users (id, name, email) VALUES ($1, $2, $3) RETURNING *',
           [profile.id, profile.name, profile.email]);
       return done(null, users[0] || null);
     } catch (err) {
       console.error(err);
       return done(err, null);
     }
   })();
 }
Ejemplo n.º 27
0
      beforeEach(() => {
        const knex = session.knex;

        return Promise.coroutine(function *() {
          yield Animal.query(knex).delete();
          yield Person.query(knex).delete();
          yield Person.query(knex).insertGraph({
            id: 1,
            name: 'Arnold',

            pets: [{
              id: 1,
              name: 'Fluffy'
            }]
          });
        })();
      });
Ejemplo n.º 28
0
export function async(obj, func, ...args) {
  if (typeof obj == "function") {
    [func, obj] = [obj, null];
  }

  if (typeof obj == "object") {
    func = func.bind(obj);
  }

  BB.coroutine.addYieldHandler(function(yieldedValue) {
    if (typeof yieldedValue !== 'function') {
      return BB.resolve(yieldedValue);
    }
  });

  return BB.coroutine(func).apply(func, [...args]);
}
var getPackage = function () {
  var _ref2 = bluebird.coroutine(regeneratorRuntime.mark(function _callee2(dir, cache) {
    var pack, out;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (!cache.has(dir)) {
              _context2.next = 2;
              break;
            }

            return _context2.abrupt('return', cache.get(dir));

          case 2:
            _context2.prev = 2;
            _context2.next = 5;
            return readFile$1(path.join(dir, 'package.json'));

          case 5:
            pack = _context2.sent;
            out = JSON.parse(pack);

            cache.set(dir, out);
            return _context2.abrupt('return', out);

          case 11:
            _context2.prev = 11;
            _context2.t0 = _context2['catch'](2);

            cache.set(dir, false);
            return _context2.abrupt('return');

          case 15:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this, [[2, 11]]);
  }));

  return function getPackage(_x4, _x5) {
    return _ref2.apply(this, arguments);
  };
}();
Ejemplo n.º 30
0
    it('team test', function(cb){
        var app = env.createApp('team-server-1', 'team');

        P.coroutine(function*(){
            yield P.promisify(app.start, app)();

            var teamController = app.controllers.team;
            var playerController = app.controllers.player;
            yield app.memdb.goose.transaction(P.coroutine(function*(){
                var playerId = yield playerController.createAsync({
                    authInfo: {socialId : '123', socialType: consts.binding.types.DEVICE},
                    name : 'rain'
                });
                var teamId = yield teamController.createAsync(playerId, {name : 'area1'});
                var players = yield teamController.getPlayersAsync(teamId);
                players.length.should.eql(1);
                players[0]._id.should.eql(playerId);

                yield playerController.connectAsync(playerId, 'c1');
                yield teamController.pushAsync(teamId, null, 'chat', 'hello', true);
                var msgs = yield teamController.getMsgsAsync(teamId, 0);
                msgs.length.should.eql(1);
                msgs[0].msg.should.eql('hello');

                var playerId1 = yield playerController.createAsync({
                    authInfo: {socialId : '1234', socialType: consts.binding.types.DEVICE},
                    name : 'rain1'
                });
                yield teamController.joinAsync(teamId, playerId1);

                var team = yield app.models.Team.findByIdAsync(teamId);
                team.playerIds.toObject().should.eql([playerId, playerId1]);

                yield teamController.quitAsync(teamId, playerId);
                yield playerController.removeAsync(playerId);

                players = yield teamController.getPlayersAsync(teamId);
                players.length.should.eql(1);

            }), app.getServerId());

            yield P.promisify(app.stop, app)();
        })()
        .nodeify(cb);
    });