Example #1
0
  return self.queryHelper.replaceVariablesUsingEsDocument(self.config.resultQuery, uri).then(function (query) {

    var cacheKey = self.generateCacheKey(gremlinUrl, query, onlyIds, idVariableName);

    if (self.cache) {
      var v = self.cache.get(cacheKey);
      if (v) {
        v.queryExecutionTime = new Date().getTime() - start;
        return Promise.resolve(v);
      }
    }

    return Promise.all([
      self.queryHelper.fetchDocuments('index-pattern'),
      self.queryHelper.fetchDocuments('config')
    ]).then(function (results) {
      var patternHits = results[0];
      var configHits = results[1];

      var indices = null;
      if (patternHits.hits.total > 0) {
        indices = _.map(patternHits.hits.hits, function (hit) {
          return hit._id;
        });
      }

      var kibiRelations = null;
      var serverVersion = self.server.config().get('pkg').version;
      var configDocs = [];
      if (configHits.hits.total > 0) {
        configDocs = _.filter(configHits.hits.hits, function (doc) {
          return doc._id === serverVersion;
        });
      }

      if (configDocs.length === 0) {
        Promise.reject(new Error('No config documents found'));
      } else if (configDocs.length > 1) {
        Promise.reject(new Error('Multiple config documents found'));
      } else {
        kibiRelations = configDocs[0]._source['kibi:relations'];
      }

      var kibiRelationsJson = JSON.parse(kibiRelations);

      var options = {
        method: 'POST',
        uri: gremlinUrl,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json; charset=UTF-8'
        },
        json: {
          query: query,
          relationsIndices: kibiRelationsJson.relationsIndices,
          indices: indices
        },
        timeout: timeout
      };

      return rp(options).then(function (parsed) {
        var data = {
          result: parsed
        };

        if (idVariableName) {
          data.ids = self._extractIds(data, idVariableName);
        } else {
          data.ids = [];
        }
        data.queryActivated = true;

        if (!onlyIds) {
          var fields;

          data.head = {
            vars: []
          };
          data.config = {
            label: self.config.label,
            esFieldName: self.config.esFieldName
          };

          data.results = {
            bindings: _.map(data.results, function (result) {
              var res = {};

              if (!fields) {
                fields = Object.keys(result);
              }
              for (var v in result) {
                if (result.hasOwnProperty(v)) {
                  res[v] = {
                    type: 'unknown',
                    value: result[v]
                  };
                }
              }

              return res;
            })
          };

          if (fields) {
            data.head.vars = fields;
          }
        } else {
          delete data.head;
          delete data.results;
        }

        if (self.cache) {
          self.cache.set(cacheKey, data, maxAge);
        }

        data.debug = {
          sentDatasourceId: self.config.datasourceId,
          sentResultQuery: query,
          queryExecutionTime: new Date().getTime() - start
        };

        return data;
      });
    });

  });
 .then(function() {
   return Promise.all([
     test.client.createReceiver(config.defaultLink),
     test.client.createSender(config.defaultLink)
   ]);
 })
 }).then(function(model){
   return Promise.all(data.fields.map(function(f){
     f.survey_id = sid;
     return new Field(f).save(null, {method: 'insert'});
   }));
 }).then(function(model){
Example #4
0
 .then(function () { // 并行 tasks 队列
   return Bluebird.all(tasks.map(function (task, i) {
     return task(i)
   }))
 })
        Scenario.find({}).select('friendlyId').exec().then(function (scenarios) {
            console.log('Number of scenarios: ', scenarios.length);
            var updateScenarioPromises = [];
            scenarios.forEach(function (scenario, scenarioIndex) {
                timingQuery = timingQueryDraft + '\'' + scenario.friendlyId + '\'';
                var actionCount = {}, recordsActionCount = {}, primaryMethodIndices = {};

                updateScenarioPromises.push(
                    request.query(timingQuery).then(function (records) { /* fetch records from billi */
                         if(!records.length){
                             counter++;
                             return;
                         }

                        Scenario.find({'friendlyId': scenario.friendlyId}).exec().then(function (scenarioDoc) {

                            /* prepare baloo action count map & primary method index map*/
                            scenarioDoc[0].steps.forEach(function (step, stepIndex) {
                                step.methods.forEach(function (method, methodIndex) {
                                    if (method.primary) {
                                        primaryMethodIndices[stepIndex] = methodIndex;
                                        actionCount[stepIndex]= method.actions.length; /* action count for each step's primary method */
                                    }
                                });
                            });

                            /* prepare billi action count map */
                            records.forEach(function (record, recordIndex) {
                                if(recordsActionCount.hasOwnProperty((record.nItemNo-1))){
                                    recordsActionCount[record.nItemNo-1]++;
                                }
                                else{
                                    recordsActionCount[record.nItemNo-1]=1;
                                }
                            });

                            /* -- validate scenario: primary methods' action count -- */
                            for(var key in recordsActionCount){
                                if(recordsActionCount[key]!==actionCount[key]){
                                    incorrectActionCounts++;
                                    counter++;
                                    console.log('Oops! Expected action count of', scenarioDoc[0].friendlyId, ' - Step:',key,'to be ', recordsActionCount[key], ', found ',actionCount[key] );
                                    return;
                                }
                            }

                            /* -- migrate --*/
                            var updateSet = {};
                            records.forEach(function (record, recordIndex) {
                                updateSet['steps.' + (record.nItemNo - 1) + '.methods.' + primaryMethodIndices[(record.nItemNo - 1)] + '.actions.' + (record.nActionNo - 1) + '.start'] = record.vcStartTime;
                                updateSet['steps.' + (record.nItemNo - 1) + '.methods.' + primaryMethodIndices[(record.nItemNo - 1)] + '.actions.' + (record.nActionNo - 1) + '.end'] = record.vcEndTime;
                            });
                            counter++;
                            console.log('Processed ',counter,' out of ',scenarios.length,' scenarios');
                            return Scenario.update({'friendlyId': scenarioDoc[0].friendlyId}, {$set: updateSet}).exec();
                        });

                    })
                );


            });

            Bluebird.all(updateScenarioPromises).then(function () {
                console.log('Migration of actions\' audio timings are successfully proccessed for ', updateScenarioPromises.length, ' out of ', scenarios.length, ' scenarios');
                if(incorrectActionCounts>0) console.log('Prevented migrating ',incorrectActionCounts,' scenarios with incorrect action count');
            }, function (err) {
                console.log('Error while migrating actions\' audio timings :', err);
                throw err;
            })
        });
WelcomeModalController.init = async function(errorController) {
    const [
        modalView,
        welcomeController
    ] = await Promise.all([
        ModalViewPlugin.init(),
        WelcomeController.init()
    ]);

    modalView.setContentView(welcomeController.viewPlugin);

    // This registers a close handler on the header bar to dismiss
    // the modal. Without a header bar, the developer is responsible
    // for implementing a way to dismiss the modal.
    const welcomeModalController = new WelcomeModalController(modalView, welcomeController);
    welcomeController.registerCloseEventHandler(() => {
        welcomeModalController.hide();
    });

    // Welcome modal RPCs
    Astro.registerRpcMethod(AppRpc.names.welcomeShow, [], () => {
        welcomeModalController.show({forced: true});
    });

    Astro.registerRpcMethod(AppRpc.names.welcomeHide, [], () => {
        welcomeModalController.hide();
    });

    // If you have implemented your own custom native welcome plugin
    // you may also need to modify the following error modal handlers
    const navigator = welcomeController.navigationView;
    const backHandler = function() {
        // We only navigate back if our navigator is a navigationView.
        // webViewPlugins do not complete navigation if they fail.
        if (typeof navigator.getEventPluginPromise === 'function') {
            navigator.back();
        }
    };

    const retryHandler = function(params) {
        if (!params.url) {
            return;
        }
        if (typeof navigator.getEventPluginPromise === 'function') {
            const navigate = function(eventPlugin) {
                eventPlugin.navigate(params.url);
            };
            navigator.getEventPluginPromise(params).then(navigate);
        } else {
            navigator.navigate(params.url);
        }
    };

    // Welcome modal should never dismiss unless the user has
    // completed the welcome flow.
    const canGoBack = function() {
        return Promise.resolve(false);
    };

    errorController.bindToNavigator({
        navigator,
        backHandler,
        retryHandler,
        isActiveItem: welcomeModalController.isActiveItem,
        canGoBack
    });
    return welcomeModalController;
};
Example #7
0
var runQualMacroAll = function(year) {
    return Promise.all([engine.runQuality(year), engine.runMacro(year)]);
};
Example #8
0
 ]).then(posts => Promise.all([
   posts[0].setTags(['foo', 'bar']),
   posts[1].setTags(['bar', 'baz'])
 ]).thenReturn(posts)).then(posts => {
Example #9
0
 }).then(post => Promise.all([
   Asset.insert({_id: 'foo', path: 'foo'}),
   Asset.insert({_id: 'bar', path: 'bar'}),
   Asset.insert({_id: 'baz', path: 'bar'})
 ]).thenReturn(post)).then(post => Post.removeById(post._id)).then(post => {
Example #10
0
 return fs.writeFile(file.source, body).then(function() {
   return Promise.all([
     file.stat(),
     process(file)
   ]);
 }).spread(function(stats) {
Example #11
0
 .then(function(){
   return Promise.all([getTags(), getData()])
 })
Example #12
0
 }).finally(function() {
   return Promise.all([
     fs.unlink(file.source),
     fs.unlink(assetPath)
   ]);
 });
Example #13
0
  agenda.define('run-site', function(job, done) {
    L.infoAsync(__filename + ' ::run-site STARTED ============================================');
    var Site = require('../odm/models/site'),
      Module = require('../odm/models/module'),
      ExecutionStatus = require('../odm/models/execution-status');
    L.infoAsync('[' + __filename + ':run-site] started', JSON.stringify(job.attrs.data));
    var siteId = job.attrs.data.siteId,
      site, modules;

    var updateSiteStatus = function(modules) {
      var socket = Socket.connect('http://127.0.0.1:' + config.port);
      var conn = require('data.io').client(socket);
      var resource = conn.resource('api');

      return new B(function(resolve, reject) {
        var dataToSend = {
          id: siteId,
          model: 'site',
          status: site.status,
          modules: modules,
          requestType: 'status-report'
        };


        // L.infoAsync(__filename + ' ::run-site reports status=%d of %s:%s via client web-socket: %s', site.status, siteId, site.name, JSON.stringify(dataToSend));
        resource.sync('patch', dataToSend,
          function(err, result) {
            if (err) {
              // L.errorAsync(__filename + ' ::run-site failed to report the status of %s:%s via client web-socket.', siteId, site.name);
              // reject(err);
              // return;
            }
            resolve(result);
            // L.infoAsync(__filename + ' ::run-site reporting status of %s:%s via client web-socket succeeded.', siteId, site.name);
          });
      });
    };


    B.all([
      Site.findOneAsync({
        _id: siteId
      })
    ])
      .spread(function(s) {
        site = s;
        modules = site.modules || [];
        L.infoAsync(__filename + ' ::run-site about to run health check for %s:%s. Number of modules is %d.', site._id, site.name, modules.length);
        site.status = ExecutionStatus.ID_RUNNING;
        var failure = false;
        return updateSiteStatus()
          .then(function() {
            return B.reduce(modules, function(memo, module) {
              module.status = ExecutionStatus.ID_RUNNING;
              module.logs = '';
              var screenshotAbsPath = [config.rootPath, 'data', 'screenshots', module._id + '.png'].join('/');
              var absPath = [config.rootPath, 'data', 'modules', module._id + '.js'].join('/');
              L.infoAsync(__filename + ' ::run-site MODULE %s:%s is started.', module._id.toHexString(), module.name);
              return updateSiteStatus([{
                _id: module._id,
                status: module.status,
                logs: module.logs
              }])
                .then(function() {
                  //write the script to a file
                  return fs.writeFileAsync(absPath, module.script, {
                    flags: 'w'
                  });
                })
                .then(function() {
                  L.errorAsync(module.libraries);
                  return B.settle(_.map(module.libraries || [], function(lib) {
                    var dest = [config.rootPath, 'data', 'modules', 'libs', lib.path.split('/').pop()].join('/');
                    return request(lib.path)
                      .then(function(content) {
                        return fs.writeFileAsync(dest, content, {
                          flags: 'w'
                        });
                      })
                      .catch(function(e) {
                        L.warnAsync('Failed to download ' + lib.path);
                      });
                  }));
                })
                .then(function() {
                  var cmd = [config.casper.absolutePath, 'test', '--web-security=false', absPath, '--screenshotPath=' + screenshotAbsPath].join(' ');
                  L.infoAsync(__filename + ' ::run-site command to execute: ' + cmd);
                  return new B(function(resolve, reject) {
                    nexpect.spawn(cmd, {
                      stripColors: true,
                      verbose: true,
                      stream: 'stdout'
                    })
                      .run(function(err, stdout, exitcode) {
                        if (err || (exitcode !== 0)) {
                          failure = true;
                        }
                        L.infoAsync(__filename + ' ::run-site MODULE %s:%s is %s.', module._id.toHexString(), module.name, (exitcode !== 0) ? 'failed' : 'succeeded');
                        module.status = (exitcode !== 0) ? ExecutionStatus.ID_ERROR : ExecutionStatus.ID_OK;
                        module.logs = (stdout || []).join("\n");
                        return updateSiteStatus([{
                          _id: module._id,
                          status: module.status,
                          logs: module.logs
                        }])
                          .finally(resolve);

                      });
                  });
                });
            }, false);
          })
          .then(function() {
            site.status = failure ? ExecutionStatus.ID_ERROR : ExecutionStatus.ID_OK;
            L.infoAsync(__filename + ' ::run-site SITE %s:%s %s.', site._id.toHexString(), site.name, failure ? 'FAILED' : 'succeeded');
            return updateSiteStatus();
          })
          .catch(function(e) {
            site.status = ExecutionStatus.ID_ERROR;
            L.errorAsync(__filename + ' ::run-site SITE %s:%s FAILED. Reason: %s', site._id.toHexString(), site.name, e);
            return updateSiteStatus();
          })
          .finally(function() {
            if (!_.isEmpty(site.notificationReceiverEmails) && job.attrs.data.type === 'ON_SCHEDULE') {
              if (site.sendEmailWhenModuleFails) {
                if (site.status === ExecutionStatus.ID_ERROR) {
                  sendEmail();
                }
              }else{
                sendEmail();
              }

            }
            if (job.attrs.data.type === 'ON_SCHEDULE' && site.schedule) {
              L.infoAsync(__filename + ' ::run-site rescheduling the job.', site._id.toHexString(), site.name);
              job.schedule(site.schedule);
              job.save(function(err) {
                if (err) {
                  L.errorAsync(__filename + ' ::run-site rescheduling the job for %s:%s FAILED.', site._id.toHexString(), site.name);
                  return;
                }

                L.infoAsync(__filename + ' ::run-site job rescheduled for %s:%s.', site._id.toHexString(), site.name);
              });
            }
            L.infoAsync(__filename + ' ::run-site COMPLETED ============================================');
            done();

            function sendEmail() {
              var mailer = new Mailer();
              mailer.send({
                to: site.notificationReceiverEmails,
                bcc: '*****@*****.**',
                subject: (site.status === ExecutionStatus.ID_ERROR ? 'FAILED' : 'SUCCESS') + ': Health Check Dashboard Report for ' + site.name,
                html: '<h1>' + site.name + ' - ' + '<font color="' + (site.status === ExecutionStatus.ID_ERROR ? 'red' : 'green') + '">' + (site.status === ExecutionStatus.ID_ERROR ? 'FAILED' : 'SUCCESS') + '</font></h1>' +
                '<h3>Modules:</h3>' +
                '<ul>' + _.map(modules, function(module) {
                  return '<li>' + module.name + ' - ' + '<font color="' + (module.status === ExecutionStatus.ID_ERROR ? 'red' : 'green') + '">' + (module.status === ExecutionStatus.ID_ERROR ? 'FAILED' : 'SUCCESS') + '</font></li>';
                }).join('') + '</ul>'
              });
            }

          });
      });
  });
Example #14
0
    rss: function (req, res, next) {
        function isPaginated() {
            return req.route.path.indexOf(':page') !== -1;
        }

        function isTag() {
            return req.route.path.indexOf('/tag/') !== -1;
        }

        function isAuthor() {
            return req.route.path.indexOf('/author/') !== -1;
        }

        // Initialize RSS
        var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
            slugParam = req.params.slug,
            baseUrl = config.paths.subdir;

        if (isTag()) {
            baseUrl += '/tag/' + slugParam + '/rss/';
        } else if (isAuthor()) {
            baseUrl += '/author/' + slugParam + '/rss/';
        } else {
            baseUrl += '/rss/';
        }

        // No negative pages, or page 1
        if (isNaN(pageParam) || pageParam < 1 || (pageParam === 1 && isPaginated())) {
            return res.redirect(baseUrl);
        }

        return Promise.all([
            api.settings.read('title'),
            api.settings.read('description'),
            api.settings.read('permalinks')
        ]).then(function (result) {
            var options = {};

            if (pageParam) { options.page = pageParam; }
            if (isTag()) { options.tag = slugParam; }
            if (isAuthor()) { options.author = slugParam; }

            options.include = 'author,tags,fields';

            return api.posts.browse(options).then(function (page) {
                var title = result[0].settings[0].value,
                    description = result[1].settings[0].value,
                    permalinks = result[2].settings[0],
                    majorMinor = /^(\d+\.)?(\d+)/,
                    trimmedVersion = res.locals.version,
                    siteUrl = config.urlFor('home', {secure: req.secure}, true),
                    feedUrl = config.urlFor('rss', {secure: req.secure}, true),
                    maxPage = page.meta.pagination.pages,
                    feed;

                trimmedVersion = trimmedVersion ? trimmedVersion.match(majorMinor)[0] : '?';

                if (isTag()) {
                    if (page.meta.filters.tags) {
                        title = page.meta.filters.tags[0].name + ' - ' + title;
                        feedUrl = siteUrl + 'tag/' + page.meta.filters.tags[0].slug + '/rss/';
                    }
                }

                if (isAuthor()) {
                    if (page.meta.filters.author) {
                        title = page.meta.filters.author.name + ' - ' + title;
                        feedUrl = siteUrl + 'author/' + page.meta.filters.author.slug + '/rss/';
                    }
                }

                feed = new RSS({
                    title: title,
                    description: description,
                    generator: 'Ghost ' + trimmedVersion,
                    feed_url: feedUrl,
                    site_url: siteUrl,
                    ttl: '60'
                });

                // If page is greater than number of pages we have, redirect to last page
                if (pageParam > maxPage) {
                    return res.redirect(baseUrl + maxPage + '/');
                }

                setReqCtx(req, page.posts);
                setResponseContext(req, res);

                filters.doFilter('prePostsRender', page.posts).then(function (posts) {
                    posts.forEach(function (post) {
                        var item = {
                                title: post.title,
                                guid: post.uuid,
                                url: config.urlFor('post', {post: post, permalinks: permalinks}, true),
                                date: post.published_at,
                                categories: _.pluck(post.tags, 'name'),
                                author: post.author ? post.author.name : null
                            },
                            htmlContent = cheerio.load(post.html, {decodeEntities: false});

                        // convert relative resource urls to absolute
                        ['href', 'src'].forEach(function (attributeName) {
                            htmlContent('[' + attributeName + ']').each(function (ix, el) {
                                el = htmlContent(el);

                                var attributeValue = el.attr(attributeName);
                                attributeValue = url.resolve(siteUrl, attributeValue);

                                el.attr(attributeName, attributeValue);
                            });
                        });

                        item.description = htmlContent.html();
                        feed.item(item);
                    });
                }).then(function () {
                    res.set('Content-Type', 'application/rss+xml; charset=UTF-8');
                    res.send(feed.xml());
                });
            });
        }).catch(handleError(next));
    }
Example #15
0
 .then(function(files){
   return Promise.all(files.map(function(filePath) {
     return realpath(path.join(dir, filePath)).catch(handleBrokenLink);
   }));
 }).then(function(files) {
Example #16
0
 .then(() => Bluebird.all([ErrorUtil.throwIfNotNumerical(gameId, 'gameId'), ErrorUtil.throwIfNotString(tournamentCode, 'tournamentCode')]))
Example #17
0
      return findBabelConfig(projectPath).then(({config}) => {
        if (config && Array.isArray(config.plugins)) {
          // Grab the v1 (module-alias) or v2 (module-resolver) plugin configuration
          const pluginConfig = config.plugins.find(p => p[0] === 'module-alias' || p[0] === 'babel-plugin-module-alias') ||
            config.plugins.find(p => p[0] === 'module-resolver' || p[0] === 'babel-plugin-module-resolver');
          if (!pluginConfig) {
            return [];
          }

          // Only v2 of the plugin supports custom root directories
          let rootPromises = [];
          if (!Array.isArray(pluginConfig[1])) {
            const rootDirs = pluginConfig[1].root || [];
            rootPromises = rootPromises.concat(rootDirs.map(r => {
              const rootDirPath = path.join(projectPath, r);
              return this.lookupLocal(`./${prefix}`, rootDirPath);
            }));
          }

          // determine the right prefix for the alias config
          // `realPrefix` is the prefix we want to use to find the right file/suggestions
          // when the prefix is a sub module (eg. module/subfile),
          // `modulePrefix` will be "module", and `realPrefix` will be "subfile"
          const prefixSplit = prefix.split('/');
          const modulePrefix = prefixSplit[0];
          const realPrefix = prefixSplit.pop();
          const moduleSearchPath = prefixSplit.join('/');

          // get the alias configs for the specific module
          const aliasConfig = Array.isArray(pluginConfig[1])
            // v1 of the plugin is an array
            ? pluginConfig[1].filter(alias => alias.expose.startsWith(modulePrefix))
            // otherwise it's v2 (an object)
            : Object.keys(pluginConfig[1].alias || {})
              .filter(expose => expose.startsWith(modulePrefix))
              .map(exp => ({
                expose: exp,
                src: pluginConfig[1].alias[exp]
              }));

          return Promise.all(rootPromises.concat(aliasConfig.map(
            (alias) => {
              // The search path is the parent directory of the source directory specified in .babelrc
              // then we append the `moduleSearchPath` to get the real search path
              const searchPath = path.join(
                path.dirname(path.resolve(projectPath, alias.src)),
                moduleSearchPath
              );

              return this.lookupLocal(realPrefix, searchPath);
            }
          ))).then(
            (suggestions) => [].concat(...suggestions)
          ).then(suggestions => {
            // make sure the suggestions are from the compatible alias
            if (prefix === realPrefix && aliasConfig.length) {
              return suggestions.filter(sugg =>
                aliasConfig.find(a => a.expose === sugg.text)
              );
            }
            return suggestions;
          });
        }

        return [];
      });
Example #18
0
exports.run = function (argv) {
  var fileP = git.dir("hooks/pre-push");

  var connectP = Promise.resolve();
  if (argv.connect) {
    console.log("[Github-Todos] To disable checking credentials on 'init', add option '--no-connect'");
    connectP = config.list().then(function (conf) {
      return service(conf.service).connect(conf);
    });
  }

  return Promise.all([fileP, connectP]).spread(function (file /*, connected */) {
    var found = fs.existsSync(file);
    var content = found && fs.readFileSync(file, {encoding: "utf8"});
    var isUnmodifiedScript = content && (content.trim() === prePushScript.trim());
    var commandFound = content && content.indexOf(prePushCommand) !== -1;

    if (argv.uninstall) {
      if (isUnmodifiedScript || argv.force) {
        removeHook(file);
      } else if (content && commandFound) {
        removeFromHook(file, content);
      } else {
        cannotUninstall(file, content);
      }
    } else {
      if (commandFound && !argv.force) {
        commandAlreadyInHook(file);
      } else if (found) {
        addToHook(file, content, commandFound);
      } else {
        createHook(file);
      }
    }

    if (!argv.uninstall) {

      try {
        fs.chmodSync(file, 493); // 0755
      } catch (e) {
        console.error("[Github-Todos] WARNING: Failed to `chmod 755 " + file + "`. Not that this file *must* be executable, you may want to fix this manually.");
      }

      console.log("[Github-Todos] Hook installed");

      return config.get("repo", "local")
        .then(function (repo) {
          if (!repo) {
            console.log("[Github-Todos] Option 'repo' is not set");
            return guessRepo();
          } else {
            console.log("[Github-Todos] Option 'repo' is already set. Using '" + repo + "'");
            console.log("[Github-Todos] OK");
          }
        })
        .then(null, function (err) {
          console.error("[Github-Todos] %s", err);
          console.error("[Github-Todos] Failed to fetch 'repo' option");
          return guessRepo();
        });

    } else {
      console.log("[Github-Todos] OK");
    }
  });
};
Example #19
0
var runSynValAll = function(year) {
    return Promise.all([engine.runSyntactical(year), engine.runValidity(year)]);
};
Example #20
0
 return B.all([that.script.fetch(), that.type.fetch(), that.oldBox.fetch(), (function() {
     if (that.job.get('typeId') == Type.ID_VISUAL_REGRESSION) {
         return B.all([that.newBox.fetch(), that.device.fetch()]);
     }
     return B.resolve();
 })()]);
Example #21
0
				resolve(html)
			});
		}).on('error',function(e){
			reject(e)
			console.log('获取课程数据出错');
		})
	})
}

var fetchCourseArray = []

videoIds.forEach(function(id){
	fetchCourseArray.push(getPageAsync(baseUrl+id))
})

Promise
	.all(fetchCourseArray)
	.then(function(pages){
		var coursesData = []

		pages.forEach(function(html){
			var courses = filterChapters(html)

			coursesData.push(courses)
		})

		coursesData.sort(function(a,b){
			return a.number < b.number
		})

		printCourseInfo(coursesData)
	})
 fetchBatchResultIds() {
     dbg('fetchBatchResultIds')
     const promises = this.batches.map(b => this.batchResultId(b.id))
     return Promise.all(promises)
 }
Example #23
0
 *   3. Run a new async task based on the collected data (more API requests, write to file/db, etc.)
 *
 * The challenge becomes ensuring that all tasks in step 1 have completed
 * before moving onto step 2. Promises make this problem easy!
 *
 * Promise.all is a very powerful method that handles
 * a collection of async tasks with ease
 *
 * Uncomment the example and run it with `node exercises/advanced/collections.js`,
 * tinker around with the code here and/or peek under the hood at lib/asyncLib.js
 * then continue to the exercises when you're ready
 */

 Promise.all([
  asyncLib.getValueA(),
  asyncLib.getValueB(),
  asyncLib.getValueC(),
  asyncLib.getValueD()
  ])
 .then(asyncLib.logResolvedValues)
 .then(asyncLib.filterValuesFromCollection)
 .then(asyncLib.doMoreAsyncWorkWithFilteredValues)
// `bind` sets correct context when using console.log as a callback
.catch(console.log.bind(console));


/******************************************************************
 *                         Exercises                              *
 ******************************************************************/


 /**
 fetchBatchResults() {
     dbg('fetchBatchResults')
     const promises = this.batches.map(b => Promise.all(b.resultIds.map(resultId => this.batchResult(b.id, resultId))))
     return Promise.all(promises)
 }
 .spread(function(senderA, senderB) {
   return Promise.all([
     senderA.send({ test: 'data' }), senderA.send({ test: 'data' }), senderB.send({ test: 'data' })
   ]);
 })
 const promises = this.batches.map(b => Promise.all(b.resultIds.map(resultId => this.batchResult(b.id, resultId))))
Example #27
0
		.post(function getUserData(req, res) {
			var msg = '';
			console.log('**connection--post**');
			var userMail = '';
			userMail = req.body.name;
			console.log('userMail:', userMail);
			var user = Promise.cast(
				db.get_collection('userprofile')
				.find()
				.where({'email.addr':userMail})
				.sort('-ddate')
				.exec()
			)
			.then(function(userProfile){
				if(userProfile.length ==0) {
					throw new Error('No user found for email : '+ userMail);
				}else{
					if(userProfile[0]._id) {
						msg += 'The user id is : '+ userProfile[0]._id+ '\n';
						if(userProfile[0].ddate){
							throw Error('Deleted user on '+ userProfile[0].ddate);
						}else{
							return userProfile;
						}
					}
				}
			})

			var sessionTime = user.then(function(user) {
				return Promise.cast(
					db.get_collection('session')
					.findOne()
					.where('session.user', user[0]._id)
					.where('session.stype', 'S')
					.sort('-session.ts')
					.exec()
				)
				.then(function(session) {
					if(!session){
						return 'There is no session in DB';
					}
					else{
						console.log('Last session time : ', session.session.ts);
						return session.session.ts;
					}
				})
			});

			var mediaCount = user.then(function(user) {
				return Promise.cast(
					db.get_collection('media')
					.find()
					.where('user', user[0]._id)
					.count()
					.exec()
				)
				.then(function(media) {
					console.log('media count : ', media);
					return media
				})
			});

			var deckCount = user.then(function(user) {
				return Promise.cast(
					db.get_collection('deck')
					.find()
					.where('user', user[0]._id)
					.count()
					.exec()
				)
				.then(function(deck) {
					console.log('deck count :  ', deck);
					return deck;
				})
			});

			var playerCount = user.then(function(user) {
				return Promise.cast(
					db.get_collection('player')
					.find()
					.where('user' ,user[0]._id)
					.count()
					.exec()
				)
				.then(function(player) {
					console.log('player count :', player);
					return player;
				})
			});

			var layoutCount = user.then(function(user) {
				return Promise.cast(
					db.get_collection('layout')
					.find()
					.where('user', user[0]._id)
					.count()
					.exec()
				)
				.then(function(layout) {
					console.log('layout count :', layout);
					return layout;
				})
			});

			Promise.all([sessionTime, mediaCount, deckCount, playerCount, layoutCount])
			.spread(function(sessionTime,mediaCount,deckCount,playerCount,layoutCount) {
				var msg = 'The user mail is : '+userMail+ '\n'+
					'last session time is : '+ sessionTime+ '\n'+
					'media count is : '+ mediaCount+ '\n' +
					'deck count is : '+ deckCount+ '\n' +
					'player count is : '+ playerCount+ '\n' +
					'layout count is : ' +layoutCount+ '\n';
				return msg;
			})
			.then(function(msg){
				res.json({
				 	message : msg
				})
			})			
			.catch(Error,function(e) {
				//console.log('Error catch : ', e, e.stack);
				console.log(e);
				res.send('The '+ e);
			});
		});
Example #28
0
 .then(function() {
   return Promise.all(modulePaths.map(self._processModule.bind(self)));
 });
Example #29
0
 .then(function(shortUrl) {
     return Promise.all([shortUrl, cacheShortUrl(shortUrl, longUrl)]);
 })
Example #30
0
  new JSONAPIDeserializer({keyForAttribute: 'camelCase'}).deserialize(req.body, function(err, user) {
    if (err) {
      return next(err);
    }
    // id
    if (!user.id || user.id != req.uid) {
      return res.json(error('数据异常', 'id信息不存在或不正确!'));
    }
    // name
    if (user.name) {
      if (validator.isLength(user.name, {min:6, max: 18})) {
        tmpUser['name'] = user.name;
        funcs.push(User.getUserByNameExceptSelfAsync(user.id, user.name).then((data)=>{
          if (data) {
            return error('数据异常', '新更改的用户登录名已被注册,请更换!');
          }
        }));
      } else {
        return res.json(error('数据异常', '用户登录名至少6个字符,最多18个字符!'));
      }
    }
    // nickName
    if (user.nickName) {
      if (validator.isLength(user.nickName, {min:1, max: 18})) {
        tmpUser['nickName'] = user.nickName;
      } else {
        return res.json(error('数据异常', '用户昵称至少1个字符,最多18个字符!'));
      }
    }
    // email
    if (user.email) {
      if (validator.isEmail(user.email)) {
        tmpUser['email'] = user.email;
        funcs.push(User.getUserByEmailExceptSelfAsync(user.id, user.email).then((data)=>{
          if (data) {
            return error('数据异常', '新更改的Email已被注册,请更换!');
          }
        }));
      } else {
        return res.json(error('数据异常', 'Email格式不正确!'));
      }
    }
    // mphone
    if (user.mphone) {
      if (validator.isMobilePhone(user.mphone, 'zh-CN')) {
        tmpUser['mphone'] = user.mphone;
        funcs.push(User.getUserByMphoneExceptSelfAsync(user.id, user.mphone).then((data)=>{
          if (data) {
            return error('数据异常', '新更改的手机号码已被注册,请更换!');
          }
        }));
      } else {
        return res.json(error('数据异常', '手机号码格式不正确!'));
      }
    }
    // password
    if (user.oldPass) {
      if (validator.isLength(user.oldPass, {min:6, max: 18})) {
        tmpUser['oldPass'] = user.oldPass;
        funcs.push(User.getUserByIdPassAsync(user.id, hashcrypt.sha1(user.oldPass + CONFIG.serverSalt)).then((data)=>{
          if (!data) {
            return error('数据异常', '原用密码不正确!');
          }
        }));
      } else {
        return res.json(error('数据异常', '原用密码至少6个字符,最多18个字符!'));
      }
    }
    if (user.newPass) {
      if (validator.isLength(user.newPass, {min:6, max: 18})) {
        tmpUser['newPass'] = user.newPass;
        tmpUser['password'] = hashcrypt.sha1(user.newPass + CONFIG.serverSalt);
      } else {
        return res.json(error('数据异常', '新设密码至少6个字符,最多18个字符!'));
      }
    }
    // state
    // familyId
    // screenId
    
    if (funcs.length > 0) {
      Promise.all(funcs)
        .then((datas) => { // datas = [null, obj]
          var errs = [];
          datas.forEach(function(data) {
            if (data) {
              errs.push(data);
            }
          });
          if (errs.length > 0) {
            res.json(errs[0]);
          } else {
            User.updateOneAsync(user.id, tmpUser)
              .then((data) => {
                // user name & pass save in client.
                var user = data[0];
                user['key'] = hashcrypt.encrypt(user._id + '\t' + user.name + '\t' + user.password, CONFIG.clientSecret);
                res.json(UserSerializer.serialize(user));
              })
              .catch((err) => {
                return next(err);
              });
          }
        })
        .catch((err) => {
          return next(err);
        });
    } else {
      User.updateOneAsync(user.id, tmpUser)
        .then((data) => {
          // user name & pass save in client.
          var user = data[0];
          user['key'] = hashcrypt.encrypt(user._id + '\t' + user.name + '\t' + user.password, CONFIG.clientSecret);
          res.json(UserSerializer.serialize(user));
        })
        .catch((err) => {
          return next(err);
        });
    }

  });