附加中间件

@param {Object} app App对象
@param {Object} options 配置项
12954
function attachMiddleware(app, options) {
    // 日志中间件
    app.use(log.express());
    // 初始化中间件
    app.use(require('./lib/middleware/init'));
    // 设置上下文
    app.use(setContext);

    // 附加自定义中间件
    beforeMiddlewares.forEach(function (fn) {
        app.use(fn);
    });

    // 路由绑定
    router.use(app);

    // 附加自定义中间件
    afterMiddlewares.forEach(function (fn) {
        app.use(fn);
    });

    // 页面渲染中间件
    var renderHTML = require('./lib/middleware/renderHTML');
    app.use(renderHTML({
        templateData: options.templateData,
        indexFile: options.indexFile
    }));
    // 错误处理
    app.use(require('./lib/middleware/error'));
}
1211374
function(app) {
  if (process.env.POMELO_LOGGER !== 'off') {
    var env = app.get(Constants.RESERVED.ENV);
    var originPath = path.join(app.getBase(), Constants.FILEPATH.LOG);
    var presentPath = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.LOG));
    if(fs.existsSync(originPath)) {
      log.configure(app, originPath);
    } else if(fs.existsSync(presentPath)) {
      log.configure(app, presentPath);
    } else {
      logger.error('logger file path configuration is error.');
    }
  }
}
648208
def init_app(app, *storages):
    '''
    
    '''

    # Set default configuration
    app.config.setdefault('FS_SERVE', app.config.get('DEBUG', False))
    app.config.setdefault('FS_ROOT', join(app.instance_path, 'fs'))
    app.config.setdefault('FS_PREFIX', None)
    app.config.setdefault('FS_URL', None)
    app.config.setdefault('FS_BACKEND', DEFAULT_BACKEND)
    app.config.setdefault('FS_IMAGES_OPTIMIZE', False)

    state = app.extensions['fs'] = app.extensions.get('fs', {})
    for storage in storages:
        storage.configure(app)
        state[storage.name] = storage

    from .views import bp
    app.register_blueprint(bp, url_prefix=app.config['FS_PREFIX'])
1081890
function initialize(app, options) {
  var log = logger.get(options);
  app._mukoan = app._mukoan || {};
  if (!app._mukoan.initialized) {
    var config = defaults({}, options, DEFAULT_CONFIGURATION);
    log.info('Starting and configuring Koa server');

    // Setup global error handler and logger
    app.use(middlewares.error(config.error));
    app.on('error', (error) => log.error('Unexpected exception ', error));
    app._mukoan.initialized = true;
  } else {
    log.warn('Trying to initialize the same Koa instance twice (ignoring action)');
  }
}
164680
function SettingsFile(app, options) {
  if (!app) {
    throw new TypeError('SettingsFile must accept an app name');
  }
  else if (typeof app !== 'string') {
    throw new TypeError('SettingsFile app name must be a string');
  }

  debug('initialize new settings file for app: %s', app);
  this._app = app;
  this._path = nachosHome('data', app + '.json');
  debug('resolved path is %s', this._path);
  this._options = defaults(options, {
    globalDefaults: {},
    instanceDefaults: {}
  });
}
438550
def init_app(self, app):
        

        self.app = app

        self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url)
        self.allow_absolute_url = self.app.config.get('APIDOC_ALLOW_ABSOLUTE_URL', self.allow_absolute_url)

        url = self.url_path

        if not self.url_path.endswith('/'):
            url += '/'

        app.add_url_rule(url, 'docs', self.__send_static_file, strict_slashes=True)
        app.add_url_rule(url + '<path:path>', 'docs', self.__send_static_file, strict_slashes=True)
593124
function(options)
	{
		options = conbo.clone(options || {});
		options.app = this;
		
		this.context = new this.contextClass(options);
	}
1173815
function(apps) {

  var filepath = getGlobalConfig().appRegistry;

  var tempFilepath = filepath + '.tmp';

  // Write to temp file.
  return Promise.fromNode(function(cb) {
    fs.writeFile(tempFilepath, JSON.stringify(apps), cb);
    log.debug(format('Setting app registry with %j', apps));
  })
  // Rename temp file to normal file.
  .then(function() {
    return Promise.fromNode(function(cb) {
      fs.rename(tempFilepath, filepath, cb);
    });
  });

}
1226716
function(userConf, template, callback) {

        var content = userConf,
        //if nothing to merge.
            newContent = JSON.parse( JSON.stringify(content) );

        var isStandalone = true,
            env = self.Env.get(),
            appsPath = "",
            modelsPath = "";


        //Pushing default app first.
        self.bundles.push(self.startingApp);//This is a JSON.push.
        var root = new _(self.executionPath).toUnixStyle();
        try {
            var pkg = require(_(root + '/project.json')).bundles;
        } catch (err) {
            callback(err);
        } //bundlesPath will be default.


        //For each app.
        for (var app in content) {
            //Checking if genuine app.
            console.debug('Checking if application [ '+ app +' ]is registered ');

            if ( typeof(content[app][env]) != "undefined" ) {

                if (
                    pkg[app] != 'undefined' && pkg[app]['src'] != 'undefined' && env == 'dev'
                    || pkg[app] != 'undefined' && pkg[app]['src'] != 'undefined' && env == 'debug'
                ) {
                    var p = _(pkg[app].src);
                    content[app][env]['bundlesPath'] = "{executionPath}/"+ p.replace('/' + app, '');
                } else {
                    var p = ( typeof(pkg[app].release.link) != 'undefined' ) ? _(pkg[app].release.link) : _(pkg[app].release.target);
                    content[app][env]['bundlesPath'] = "{executionPath}/"+ p.replace('/' + app, '');
                }

                appsPath = (typeof(content[app][env]['bundlesPath']) != "undefined")
                    ? content[app][env].bundlesPath
                    : template["{bundle}"]["{env}"].bundlesPath;



                modelsPath = (typeof(content[app][env]['modelsPath']) != "undefined")
                    ?  content[app][env].modelsPath
                    :  template["{bundle}"]["{env}"].modelsPath;

                //I had to for this one...
                appsPath = appsPath.replace(/\{executionPath\}/g, root);
                //modelsPath = modelsPath.replace(/\{executionPath\}/g, mPath);

                //console.log("My env ", env, self.executionPath, JSON.stringify(template, null, '\t') );
                //Existing app and port sharing => != standalone.
                if ( !fs.existsSync(appsPath) ) {
                    new _(appsPath).mkdirSync()
                }
                var masterPort = content[self.startingApp][env].port.http;
                //Check if standalone or shared instance
                if (content[app][env].port.http != masterPort) {
                    isStandalone = false;
                    self.Host.standaloneMode = isStandalone
                } else if (app != self.startingApp) {
                    self.bundles.push(app)
                }
                self.allBundles.push(app);

                //Mergin user's & template.
                newContent[app][env] = merge(
                    newContent[app][env],
                    JSON.parse( JSON.stringify(template["{bundle}"]["{env}"]))//only copy of it.
                );


                //Variables replace. Compare with gina/core/template/conf/env.json.
                var version = undefined, middleware = undefined;
                try {
                    self.version    = version = require(_(getPath('gina').root +'/package.json' )).version;
                    self.middleware = middleware = fs.readFileSync(_(getPath('gina').root + '/MIDDLEWARE')).toString() || 'none';

                    setContext('gina.version', version);
                    setContext('gina.middleware', middleware);

                } catch (err) {
                    console.debug(err.stack)
                }

                var reps = {
                    "executionPath" : root,
                    "bundlesPath" : appsPath,
                    "modelsPath" : modelsPath,
                    "env" : env,
                    "bundle" : app,
                    "version": version
                };


                //console.error("reps ", reps);
                newContent = whisper(reps, newContent);


            }
            //Else not in the scenario.

        }//EO for.


        console.debug('Env configuration loaded \n');

        // TRUE means that all apps sharing the same process will merge into one.
        if (!isStandalone) self.Host.standaloneMode = isStandalone;

        console.debug('Is server running as a standalone instance ? ' + isStandalone);

        callback(false, newContent)
    }
1118490
def init_app(self, app, **kwargs):
        """"""
        self.kwargs.update(kwargs)
        self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
        app.config = self.make_config(app)
        app.dynaconf = self.settings
731724
function toFiles(app, options) {
  let opts = Object.assign({ collection: null }, options);
  let name = opts.collection;
  let collection = app.collections ? name && app[name] : app;
  let view;

  if (!collection && name) {
    collection = app.create(name, opts);
  }

  return utils.through.obj(async (file, enc, next) => {
    if (!app.File.isFile(file)) {
      file = app.file(file.path, file);
    }

    if (file.isNull()) {
      next(null, file);
      return;
    }

    if (collection && isCollection(collection)) {
      try {
        view = await collection.set(file.path, file);
      } catch (err) {
        next(err);
        return;
      }
      next(null, view);
      return;
    }

    view = !app.File.isFile(file) ? app.file(file.path, file) : file;

    app.handle('onLoad', view)
      .then(() => next(null, view))
      .catch(next);
  });
}
112153
def init_app(self, app):
        
        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions['nav'] = self
        app.add_template_global(self.elems, 'nav')

        # register some renderers
        for args in self._renderers:
            register_renderer(app, *args)
361602
function (app) {
  let p = pathUtil.getCronPath(app.getBase(), app.getServerType());
  if (p) {
    return Loader.load(p, app);
  }
}
367478
function(app) {
  if (!appCache.good) {
    appCache.good = [];
  }
  if (!existsInCache(app, appCache.good)) {
    appCache.good.push(app);
  }
}
752618
function(app, opts) {
  opts = opts || {};
  this.app = app;
  this.channels = {};
  this.prefix = opts.prefix;
  this.store = opts.store;
  this.broadcastFilter = opts.broadcastFilter;
  this.channelRemote = new ChannelRemote(app);
}
103528
function initApp(options,app) {    
    app.set('trust proxy', 1);

    //在中间件之前使用中间件
    if(options.beforeMid) {
        options.beforeMid(app,middlewares);
    }

    //session中间件
    app.use(session(options.session));
    //cookies解析中间件
    app.use(cookieParser());
    //日志中间件
    app.use(morgan('combined'));
    //faviocn中间件
    app.use(favicon(options.public +path.sep+'favicon.ico'));
    //spm调试中间件
    if (env === 'development') {
        app.use(serveSPM(options.client, {
            log: console.log
        }));
        app.use(express.static(options.public));
    } else if (env === 'test') {
        //静态目录
        app.use(express.static(options.public));
    }

    //声明小部件目录
    hbs.registerPartials(options.partials);

    //设置handlebars视图引擎
    app.set('view engine', options.tempExt);
    app.engine(options.tempExt, hbs.__express);
    app.set('views', options.views);

    //body 序列化
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: false,
        limit:options.bodyLimit||'1000kb'
    }));

    return app;
}
1351257
function Application(options) {
    if (!(this instanceof Application)) {
        return new Application(options);
    }
    /**
     * Extend Koa
     **/
    koa.call(this);
    this.config = config(options);
    if (enable(this.config, 'logging')){
        logging.logging.configure(this.config.logging);
    }
    parsers(this, this.config.parsers);
}