Example #1
0
var koa = require('koa'),
    logger = require('koa-logger'),
    funkyname = require('funkyname.js')
    port = process.env.PORT || 8000,
    name = funkyname.getFunkyName(),
    app = koa()

app.use(logger());

app.use(function *(){
    this.body = 'This instance is called ' + name;
});

app.listen(port, function () {
    console.log('Listening on port %s', port);
});
Example #2
0
const response = require(cwd + '/middleware/response');
//################## middlewares
app.keys = config.keys;
app.use(convert(cors(
    {
        //origin: 'http://localhost,http://localhost:3000', //默认*
        exposeHeaders: ['X-My-Custom-Header', 'X-Another-Custom-Header'],
        maxAge: '86400',
        credentials: 'true',
        allowMethods: ['GET', 'POST', 'OPTION'],
        allowHeaders: ['authorization', 'X-PINGOTHER', 'Content-Type', 'x-requested-with']
    }
)))
app.use(convert(bodyparser));
app.use(convert(json()));
app.use(convert(logger()));
app.use(koa_static(__dirname + '/public'));
app.use(convert(hbs.middleware({
    viewPath: __dirname + '/views',
    defaultLayout: 'layout',
    layoutsPath: __dirname + '/views'
})));
/* ##################### 建表时启用 ##################### */
// const models = require(cwd + '/models');
// models.sequelize.sync().then(function () {
//     console.log("mysql connection success");
// });


app.use(convert(session({
    key: 'koa:session',//session key
Example #3
0
'use strict';
var koa = require('koa');

var logger = require('koa-logger');
var serve = require('koa-static');
var router = require('koa-router')();
var scheduler = require('./controllers/scheduler');
var bodyParser = require('koa-body-parser');

var app = module.exports = koa();

router
  .post('/log', scheduler.log)
  .post('/search', scheduler.search)
  .post('/login', scheduler.login)
  .post('/save', scheduler.save)
  .post('/remove', scheduler.remove);

app
  .use(logger())
  .use(bodyParser())
  .use(serve('public'))
  .use(router.routes())
  .use(router.allowedMethods());

if (!module.parent) {
  app.listen(process.env.USER_APP_PORT || 9899);
}
Example #4
0
    this.state.debug = config.debug;
    yield next;
});


app.use(staticCache(staticDir,{
    maxAge: 365 * 24 * 60 * 60
}));

//app.use(staticCache(staticDir+'/js'));
//app.use(staticCache(staticDir+'/css'));

//控制台访问日志
if(config.debug){
    var koaLogger = require('koa-logger');
    app.use(koaLogger());
}


//路由
var router = require('koa-router');


app.use(function *(next) {
    //yield next;
    try {
        yield next;
    } catch (err) {
        console.log(err);
        //logger.error(err);
        this.status = err.status || 500;
Example #5
0
/*!
 * Moajs Middle
 * Copyright(c) 2015-2019 Alfred Sang <*****@*****.**>
 * MIT Licensed
 */
require('../../config/log.js')

const logger = require('koa-logger')

// 检查用户会话
module.exports = logger()
Example #6
0
app.use(compress());

function ignoreAssets(mw) {
  return function *(next) {
    if (/(\.js|\.css|\.ico|\.jpg|\.woff2)$/.test(this.path)) {
      yield next;
    } else {
      // must .call() to explicitly set the receiver
      // so that "this" remains the koa Context
      yield mw.call(this, next);
    }
  }
}
// https://github.com/koajs/logger
// app.use(ignoreAssets(logger('dev')));
app.use(logger('dev'));
// https://github.com/koajs/bodyparser
app.use(bodyParser({
  onerror: function (err, ctx) {
    ctx.throw('body parse error', 422);
  }
}));
// https://github.com/koajs/favicon
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
// https://github.com/koajs/static
app.use(serve(path.join(__dirname, 'public'), {
  maxAge: 365 * 24 * 60 * 60 * 1000,
}));

var router = require('./router');
app.use(router.routes());
Example #7
0
var router = require('koa-router');
var Logger = require('koa-logger');
var serve = require('koa-static');
var views = require('koa-views');
var formidable = require('koa-formidable');
var session = require('koa-generic-session');
var bunyan = require('bunyan');
var passport = require('koa-passport');

var User = require('./user');
var mongoose = require('./mongoose');


var app = koa();

app.use(Logger());

app.use(function* (next) {

	this.requestID = Math.random();

	this.log = bunyan.createLogger({
		name: 'app',
		requestID: this.requestID,
		stream: process.stdout,
		level: 'info'
	});

	try {
		yield* next;
	} catch (e) {
Example #8
0
function middleware_main(app) {

app.keys = [key_config.SESSION_KEY];

// middleware
app.use(logger());
//app.use(json({ pretty: false }));

app.use(session({maxAge: COOKIE_MAXAGE}, app));

app.use(function *(next) {
  var have_files = false;
  if (this.request.is('multipart/*')) {
    var parts = multipartparse(this);
    var part;
    var body = {};
    var files = {};
    while (part = yield parts) {
      if (part.length) {
        // arrays are busboy fields
        body[part[0]] = part[1];
      } else {
        // otherwise, it's a stream
        var extName = path.extname(part.filename);
        var tmpFileName = makeuniqueid(16);
        var savepath = path.resolve(sys_config.tmp_dir + tmpFileName);
        part.pipe(fs.createWriteStream(savepath));

        files[part.fieldname] = {
          filename: part.filename,
          mimeType: part.mimeType,
          extname: extName,
          savename: tmpFileName,
          savepath: savepath
        };

        have_files = true;
      }
    }
    this.request.body = body;
    this.request.files = files;
  } else if ('POST' == this.method) {
    try {
      var body = yield parse.json(this); //, { limit: '1kb' }
      this.request.body = body;
    } catch (e) {
      this.request.body = {};
    }
  }

  yield next;

  if (have_files) {
    //delete tmp files
    var files = this.request.files;
    for (var k in files) {
      fs.unlink(files[k].savepath, function () {});
    }
  }
});

//JSON error handling
app.use(function *pageNotFound(next) {
  yield next;
  if (404 != this.status) return;
  this.status = 404;
  this.body = {
    errno: 404,
    message: 'Page Not Found'
  };
});

app.use(function *(next) {
  try {
    yield next;
  } catch (err) {
    //this.status = 500;
    this.body = {
      errno: 500,
      message: err.toString()
    };
  }
});

}
Example #9
0
import main_routes from './api/routes/main-routes';
import plugin_loader from './app/tool/plugin_loader.js';

//import assemble from 'assemble';

//初始化
const app = new Koa();
const body_parser = new Koa_body_parser();

const env = system_config.System_type || 'development';//判断开发模式


app //初始化中间件
    .use(Koa_convert(body_parser))  //请求体解析中间件
    .use(Koa_convert(Koa_json()))   //json格式中间件
    .use(Koa_convert(Koa_logger()))
    .use(Koa_convert(Koa_favicon(path.join(__dirname, '../app/assets/img/favicon.ico'))))  //设置favicon.ico路径
    .use(Koa_convert(serve(path.join(__dirname, '../app')))) //设置静态资源路径
    .use(Koa_Nunjucks({  //Nunjucks模板引擎配置
        ext: 'html',
        path: path.join(__dirname, 'app/themes/'+system_config.System_theme+'/template'), //引入主题模板
        nunjucksConfig: {
            autoescape: false
        }
    }))
    .use(plugin_loader(system_config.System_plugin_path))
    .use(main_routes.routes())
    .use(main_routes.allowedMethods())
    //404
    .use((ctx) => {
        ctx.status = 404;
Example #10
0
import koaStatic from 'koa-static-plus'
import koaOnError from 'koa-onerror'


const app = new Koa()
const router = new Router()

/*引入路由文件*/

import index from './routes/index'
import users from './routes/users'

app
.use(convert(bodyParser()))  // post请求解析中间件
.use(convert(json()))
.use(convert(logger())) // 日志中间件
// .use(router.routes()) // 路由中间件
// .use(router.allowedMethods()) // 路由中间件
.use(convert(koaStatic(path.join(__dirname,'public'),{
  pathPrefix: ''
}))) // 静态文件指定中间件

// views
app.use(views(path.join(__dirname, '../views'), {
  extension: 'html'
}))

// 500 error
koaOnError(app, {
  template: 'views/500.html'
})
Example #11
0
// var path = require('path');
// var error = require('koa-error');
var koa = require('koa');
var appForHtml = koa();
var logger = require('koa-logger');
var compress = require('koa-compress');

var router = require('./router');
var ports = require('./config').ports;

// ---------------------------------------------------------------------------- HTML服务
// 日志
appForHtml.use(logger());

// // 错误打印
// appForHtml.use(error({
//     engine: 'ejs',
//     template: path.resolve('build/error.ejs'),
//     cache: process.env !== 'development'
// }));

// 压缩服务
appForHtml.use(compress({
    flush: require('zlib').Z_SYNC_FLUSH
}));

// 响应头
appForHtml.use(function* (next) {
    yield next;
    this.set('Content-Type', 'html');
});
Example #12
0
module.exports = function (port) {

  // inject sugarJS
  require('sugar');

  // npm dependencies
  let bodyParser = require('koa-body')({multipart: true}),
      koa = require('koa'),
      gzip = require('koa-gzip'),
      AWS = require('aws-sdk'),
      helmet = require('koa-helmet'),
      logger = require('koa-logger'),
      router = require('koa-router'),
      //session = require('koa-generic-session'),
      //RedisStore = require('koa-redis'),
      limit = require('koa-ratelimit'),
      redis = require('redis'),
      statics = require('koa-static'),
      path = require('path'),
      views = require('koa-render');

  let utils = require('./libs/utils')();

  // config AWS
  AWS.config.region = 'eu-west-1';
  let DynamoDB = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
  let db = utils.wrap(DynamoDB);

  // config coolog
  require('coolog').addChannel({
    name: 'root',
    level: 'debug',
    appenders: ['console']
  });


  let app = koa();
  // logger
  app.use(logger());

  // session
  app.keys = [process.env.SECRET_KEY];

  /*app.use(session({
    store: new RedisStore({
      host: process.env.REDIS_HOST,
      port: process.env.REDIS_PORT
    })
  }));*/

  let redis_url = require('url').parse(process.env.REDIS_URL);
  let client = redis.createClient(redis_url.port, redis_url.hostname, {no_ready_check: true});
  //client.auth(redis_url.auth.split(":")[1]);

  app.use(limit({
    db: client,
    duration: 1000 * 60 * 60,
    max: 1000
  }));


  app.use(views('./views', 'jade'));

  // serve static files
  app.use(statics(__dirname + '/public'));

  // router

  app.use(router(app));
  //app.use(require('koa-router-newrelic')(app));

  // ## Website routes

  let website_routes = require('./routes/site')(db);
  let api_routes = require('./routes/api')(db);
  let error_routes = require('./routes/error')();
  let middleware = require('./middleware')();


  // website
  let website_prefix = '';
  app.get(path.join(website_prefix, '/'), website_routes.index);
  app.get(path.join(website_prefix, '/success/:api_key'), middleware.api_key, website_routes.form.success);
  app.get(path.join(website_prefix, '/deleted'), website_routes.form.deleted);
  app.get(path.join(website_prefix, '/signup'), website_routes.form.signup);
  app.get(path.join(website_prefix, '/delete/:api_key'), middleware.api_key, website_routes.form.del);
  app.get(path.join(website_prefix, '/edit/:api_key'), middleware.api_key, website_routes.form.edit);
  app.get(path.join(website_prefix, '/dashboard/:api_key'), middleware.api_key, website_routes.dashboard);
  app.get(path.join(website_prefix, '/confirm/email/confirmed/:api_key'), middleware.api_key, website_routes.confirmed_email);
  // website errors
  app.get(path.join(website_prefix, '/520'), error_routes.origin_error);
  app.get(path.join(website_prefix, '/404'), error_routes.not_found);
  app.get(path.join(website_prefix, '/500'), error_routes.server_error);

  let api_prefix = '/api';
  app.post(path.join(api_prefix, '/confirm/sms/:api_key'), bodyParser, api_routes.confirm_sms);
  app.get(path.join(api_prefix, '/confirm/send-sms/:api_key'), api_routes.send_confirm_sms);
  app.get(path.join(api_prefix, '/confirm/send-email/:api_key'), middleware.api_key, api_routes.send_confirm_email);
  app.post(path.join(api_prefix, '/new-form'), bodyParser, api_routes.form.create);
  app.post(path.join(api_prefix, '/form/:type/:api_key'), bodyParser, api_routes.form.get); //utils.rateLimit()
  app.post(path.join(api_prefix, '/edit/:api_key'), bodyParser, api_routes.form.edit);
  app.post(path.join(api_prefix, '/delete/:api_key'), bodyParser, api_routes.form.del);
  app.get(path.join(api_prefix, '/graph/:api_key'), bodyParser, api_routes.graph);

  app.get(path.join('/confirm/email/:api_key'), api_routes.confirm_email);

  // add security
  app.use(helmet.defaults());
  // compress responses
  app.use(gzip());

  // start server
  return app.listen(port);
};
Example #13
0
const PASSWORD       = process.env.PASSWORD         || 'superfakepassword';

// DATABASE POOL
const DB             = require('./lib/db');
const DB_INSTANCE    = new DB(COUCHBASE_URI, COUCHBASE_BUCK, PASSWORD);

// APP
const APP = new KOA();

// ALLOW PROXY REQUESTS
APP.proxy = true;

// RESPONSE TIME & LOGGING
APP.use(CORS());
APP.use(RESPONSE_TIME());
APP.use(LOGGER());

// SESSION
APP.keys = [SECRET];
APP.use(CONVERT(SESSION()));

// BODY PARSER
APP.use(BODY_PARSER({
  onerror: (err, ctx) => {
    ctx.throw('Error parsing the body information', 422);
  }
}));

// PASS DATABASE INSTANCE TO CTX CONTEXT
APP.use(async (ctx, next) => {
  ctx.state.db = DB_INSTANCE;
Example #14
0
module.exports = function (app) {

  app.proxy = true;

  if (config['app']['dev_mode']) {
    app.use(logger());
  }

  app.use(function *(next) {
    var have_files = false;
    if (this.request.is('multipart/*')) {
      var parts = multipartparse(this);
      var part;
      var body = {};
      var files = {};
      while (part = yield parts) {
        if (part.length) {
          // arrays are busboy fields
          body[part[0]] = part[1];
        } else {
          // otherwise, it's a stream
          var extName = path.extname(part.filename);
          var tmpFileName = hat(96, 36);
          var savepath = path.resolve(config['sys'].tmp_dir + tmpFileName);
          part.pipe(fs.createWriteStream(savepath));

          files[part.fieldname] = {
            filename: part.filename,
            mimeType: part.mimeType,
            extname: extName.toLowerCase(),
            savename: tmpFileName,
            savepath: savepath
          };

          have_files = true;
        }
      }
      this.request.body = body;
      this.request.files = files;
    } else if ('POST' == this.method) {
      this.request.body = yield parse(this);
    }

    //run next
    yield next;

    if (have_files) {
      //delete tmp files
      var files = this.request.files;
      for (var k in files) {
        fs.unlink(files[k].savepath, function () {});
      }
    }
  });

  app.use(function *(next) {
    try {
      yield next;
    } catch (e) {
      this.body = {
        code: -2,
        message: e.message
      };
    }
  });
};
Example #15
0
// Routes
router
  .redirect('/', '/habits')
  .get('/habits', habits.index)
  .get('/habits/:id', habits.show)
  .post('/habits', habits.create)
  .get('/goals', goals.index)
  .get('/goals/:id', goals.show)
  .post('/goals', goals.create)
  .post('/weights', weights.create)
  .get('/weights', weights.index);

// Middleware
app
  .use(koaBody())
  .use(koaValidate())
  .use(koaLogger())
  .use(koaCors())
  .use(koaAuth({
    name: config.userAuth,
    pass: config.userPass,
  }))
  .use(router.routes());

// Listen
app.listen(config.PORT, function() {
  console.log('Listening on %s', config.PORT);
});

export default app;
Example #16
0
// passing any middleware to this middleware
// will make it conditional, and will not be used
// when an asset is requested, illustrating how
// middleware may "wrap" other middleware.

function ignoreAssets(mw) {
  return function *(next){
    if (/(\.js|\.css|\.ico)$/.test(this.path)) {
      yield next;
    } else {
      // must .call() to explicitly set the receiver
      // so that "this" remains the koa Context
      yield mw.call(this, next);
    }
  }
}

// TRY:
// $ curl http://localhost:3000/
// $ curl http://localhost:3000/style.css
// $ curl http://localhost:3000/some.html

app.use(ignoreAssets(logger()));

app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);