コード例 #1
0
ファイル: api.js プロジェクト: gitter-badger/ForumForYou
exports = module.exports = ( routes, responsify, settings, logging, router, validate ) => {

    routes.forEach((r) => {
        let handler = r.handler,
            needsValidation = r.validate instanceof Array && r.validate.length;

        if( needsValidation ) {
            let strict = r.strict === undefined ? true : r.strict;
            handler = validate( r.validate, handler, strict );
        }

        router[ r.method ]( r.path, handler, r.handlerName );
    });

    let app = responsify( koa( ) );
    app.use(koa_static('../frontend'));
    app.use(koa_static('../frontend/src'));
    //app.use( koa_static(settings.path.appsData));
    //app.use( koa_static(settings.path.backup));
    //app.use( koa_static(settings.path.contentMedia));
    //app.use( koa_static(settings.path.firmware));
    //app.use( koa_static(settings.path.screenshot));
    app.use(livereload());
    console.log();
    app.use( logging );
    //app.use( authentification );
    app.use( koa_body( {
        jsonLimit: settings.jsonLimit,
        multipart: true,
    }));
    app.use( router.demux );

    return app;
};
コード例 #2
0
ファイル: koa.js プロジェクト: littlemooon/dash
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(livereload({excludes: ['/modules']}));
  }

  // serve the angular static files from the /client directory
  var sendOpts = {root: 'app', maxage: config.app.cacheTime};
  app.use(function *(next) {
    // skip any route that starts with /api as it doesn't have any static files
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
      return;
    }

    // if the requested path matched a file and it is served successfully, exit the middleware
    if (yield send(this, this.path, sendOpts)) {
      return;
    }
    
    // if given path didn't match any file, just let angular handle the routing
    yield send(this, '/index.html', sendOpts);
  });

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    if (file.substr(-3) === '.js') require('../controllers/' + file).init(app);
  });
};
コード例 #3
0
exports.attachMiddleware = function (app) {
  server = app.servers.koa.getServer();

  server.use(router(server));
  server.use(favicon(path.join(app.dir, '..', app.project.path.dist, '/favicon.ico')));
  server.use(compress());
  csrf(server);
  if (_.isObject(app.config.cookie) && _.isString(app.config.cookie.secret)) {
    server.keys = [app.config.cookie.secret];
  }
  server.use(session());
  if (_.isFunction(app.attachMiddleware)) {
    console.log('Attaching Project Specific Middleware');
    app.attachMiddleware();
  }


  server.use(function *(next){
    if ('POST' !== this.method) {
      return yield next;
    }

    var body = yield parse(this, { limit: '1kb' });
    if (!body.name) {
      this.throw(400, '.name required');
    }
    this.body = { name: body.name.toUpperCase() };
  });


  if(process.env.NODE_ENV === 'development') {
    server.use(serve(
      path.join(app.dir, '..', app.project.path.dist)
    ));
    server.use(logger());

    app.servers.koa.getServer().use(livereload({
      port : 35729
    }));
  }

  if (process.env.NODE_ENV === 'heroku' || process.env.NODE_ENV === 'production') {
    var maxAge = 1000 * 60 * 60 * 24 * 30;  // 1 month
    server.use(serve(
      path.join(app.dir, '..', app.project.path.dist),
      { maxAge: maxAge }
    ));

    server.on('error', function (err) {
      console.log(err.stack);
      this.response.status = 500;
      this.response.body = 'Sorry we have encountered an error.';
    });
  }
};
コード例 #4
0
ファイル: server.js プロジェクト: noraesae/net
 constructor(root) {
   this.app = new Koa();
   this.app.use(livereload());
   this.app.use(serve(root));
   this.app.use(async (ctx, next) => {
     ctx.status = 404;
     ctx.type = 'html';
     ctx.body = await readFile('./docs/404.html');
   });
   this.lrServer = createLrServer();
   this.lrServer.watch(root);
 }
コード例 #5
0
ファイル: serve.js プロジェクト: jphuisamen/food-mobile
function serve () {
  // Create the server application
  var app = koa()
  app.use(koaLivereload())
  app.use(koaStatic('www'))
  // Start the server
  app.listen(PORT)
  // Setup and start the livereload server
  var livereloadServer = livereload.createServer()
  livereloadServer.watch('www')
  // Display running server message
  log(`Server running at localhost:${PORT}`)
}
コード例 #6
0
ファイル: dev.js プロジェクト: maihq/mai-boilerplate
/**
 * Export a factory function instead of middleware
 *
 * @param   String  env  Environment name
 * @return  MW
 */
function factory(env) {
	var tools = [];

	if (env === 'dev') {
		tools.push(livereload({
			port: 30001
		}));
	}

	if (env === 'dev' || env === 'local') {
		tools.push(asset('public'));
	}

	return compose(tools);
};
コード例 #7
0
ファイル: koa.js プロジェクト: Ziink/koan
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(livereload({excludes: ['/modules']}));
  }

  // register special controllers which should come before any jwt token check and be publicly accessible
  require('../controllers/public').init(app);
  require('../controllers/signin').init(app);

  // serve the static files in the /client directory, use caching only in production (7 days)
  var sendOpts = config.app.env === 'production' ? {root: 'client', maxage: config.app.cacheTime} : {root: 'client'};
  app.use(function *(next) {
    // do not handle /api paths
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
      return;
    } else if (yield send(this, this.path, sendOpts)) {
      // file exists and request successfully served so do nothing
      return;
    } else if (this.path.indexOf('.') !== -1) {
      // file does not exist so do nothing and koa will return 404 by default
      // we treat any path with a dot '.' in it as a request for a file
      return;
    } else {
      // request is for a subdirectory so treat it as an angular route and serve index.html, letting angular handle the routing properly
      yield send(this, '/index.html', sendOpts);
    }
  });

  // middleware below this line is only reached if jwt token is valid
  app.use(jwt({secret: config.app.secret}));

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
コード例 #8
0
ファイル: koa.js プロジェクト: aslaNhuanG/aslan
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(livereload({excludes: ['/modules']}));
  }

  // register special controllers which should come before any jwt token check and be publicly accessible
  require('../controllers/public').init(app);
  require('../controllers/signin').init(app);

  // serve the angular static files from the /client directory
  var sendOpts = {root: 'client', maxage: config.app.cacheTime};
  app.use(function *(next) {
    // skip any route that starts with /api as it doesn't have any static files
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
      return;
    }
    // if the requested path matched a file and it is served successfully, exit the middleware
    if (yield send(this, this.path, sendOpts)) {
      return;
    }
    // if given path didn't match any file, just let angular handle the routing
    yield send(this, '/index.html', sendOpts);
  });

  // middleware below this line is only reached if jwt token is valid
  app.use(jwt({secret: config.app.secret}));

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
コード例 #9
0
ファイル: index.js プロジェクト: fxghqc/blog
render(app, {
  root: path.join(__dirname, 'views'),
  autoescape: true,
  cache: false,
  ext: 'html'
});

// "database"

var articles = [];

// middleware

app.use(logger());
app.use(livereload());

// route middleware

app.use(route.get('/', list));
app.use(route.get('/article/:id', show));

// route definitions

/**
 * Post listing.
 */

function *list() {
  yield this.render('list', { articles: articles });
}
コード例 #10
0
module.exports = function(){

	const koa 		 = require('koa');
	const logger 	 = require('koa-log4js');
	const bodyparser = require('koa-bodyparser');
	const favicon 	 = require('koa-favicon');
	const render 	 = require('koa-ejs');
	const util 		 = require('util');
	const path 		 = require('path');
	const serve 	 = require('koa-static');
	const livereload = require('koa-livereload');
	const config 	 = require('../bin/config');

	let env = process.env;

	let app 		 = new koa();

	app.use(livereload());

	//use static file server
	app.use(serve(`${path.resolve(__dirname,'../')}/resource/`,{
		maxage 	 :0,
		compress :false
	}));

	//use static file server
	app.use(serve(`${path.resolve(__dirname,'../')}/resource/es5/`,{
		maxage 	 :0,
		compress :false
	}));

	//use body parse mw
	app.use(bodyparser());

	//use .ico mw
	app.use(favicon(path.resolve(__dirname ,'../resource/images/favicon.ico')));

	//use template engine
	render(app, {
	  root: `${path.resolve(__dirname,'../')}/view/`,
	  layout: 'template',
	  viewExt: 'html',
	  cache: false,
	  debug: true
	});


	// rewrite render
	let sysRender = app.context.render;

	let defaultCfg = {
		js 					:['lib/require.js','lib/jq.js'],
		css 				:['css/base.css'],
		header_description 	:'xxx',
		header_keywords		:'xxx',
		header_title		:'addison'
	}

	let extendCfg = {
		sysApi 	 	 : env.api || config.api || '',
		jsServerAddr : env.jsserver || config.jsserver || '/',
		ResVer		 : env.ver || config.ver || 1	
	}

	'dev' == (env.env || config.env) && defaultCfg.js.push('http://localhost:35729/livereload.js??ver=1')

	app.context.render = function(view,opt){
		
		return function*(){
			opt = opt || {};
			
			opt.js  	= (opt.js || []).concat(defaultCfg.js);
			opt.css 	= (opt.css || []).concat(defaultCfg.css);
			opt.header_keywords 	= opt.header_keywords || defaultCfg.header_keywords;
			opt.header_title 		= opt.header_title || defaultCfg.header_title;
			opt.header_description 	= opt.header_description || defaultCfg.header_description;
			opt.layout				= opt.noLayout ? false : 'template';
			util._extend(opt,extendCfg);

			yield sysRender.apply(this,[view,opt]);
		}
	}

	//use router
	app.use(require('./middleware/router'));

	return app;
};