module.exports = (app) => {
  // session
  app.keys = ['secret1', 'secret2', 'secret3'];
  app.use(convert(session()));

  // logger
  app.use(logger());

  // view engine
  app.use(views(path.resolve(__dirname, 'views'), { extension: 'ejs' }));

  // static
  app.use(koaStatic({
    rootDir: path.resolve(__dirname, 'static'),
  }));

  // passport
  app.use(passport.initialize());
  app.use(passport.session());
  auth(passport);

  app.use(conditional());
  app.use(etag());
  app.use(body());

  app.use(async (ctx, next) => {
    ctx.body = ctx.request.body;
    await next();
  });

  app.use(new CSRF());

  onerror(app);
};
Example #2
0
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'production') {
    onerror(app);
  }
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.staticServe.isNeeded) {
    var serve = require('koa-static');
    app.use(serve(config.staticServe.root));
  } else {
    var cors = require('kcors');
    app.use(cors());
  }
  app.use(bodyParser());
  app.use(jwt({ secret: config.app.secret }).unless({ path: [/^\/api\/auth/]}));

  // mount all the routes defined in resources
  var api = new Router({prefix: '/api'});
  fs.readdirSync('./resources').forEach(function (file) {
    require('../resources/' + file).init(api);
  });
  app
    .use(api.routes())
    .use(api.allowedMethods());

};
Example #3
0
function main() {
  var app = koa();

  app.name = pkg.name;
  app.proxy = true;
  app.poweredBy = false;

  onerror(app, {template: './templates/error.html'});
  sentry(app, raven);
  trace(app);

  app.isProd = app.context.isProd = process.env.NODE_ENV === 'production';

  debug('NODE_ENV=' + process.env.NODE_ENV);

  app.context.raven = raven;

  if (!app.isProd || /koa-trace/.test(process.env.DEBUG)) app.debug();

  app.use(function*(next) {
    this.set('Timing-Allow-Origin', '*');
    yield next;
  });


  app.use(cors({
    origin: true // do something more specific here
  }));

  app.use(favicon(path.resolve(__dirname, '../public/images/favicon.ico')));
  app.use(conditional());
  app.use(etag());
  app.use(serve(path.resolve(__dirname, '../public'), {
    maxage: app.isProd ? ms('30 days') : 0,
    gzip: true
  }));
  app.use(requestId('X-Request-ID'));
  app.use(responseTime());
  app.use(printRequestId());
  app.use(function*(next){
    this.locals = this.locals || {};
    this.locals.context = this;
    yield next;
  });

  app.use(htmlMinifier({
    collapseWhitespace: true,
    minifyJS: true,
    minifyCSS: true
  }));

  if (!app.isProd) {
    debug('Using livereload');
    app.use(require('koa-livereload')());
  }

  routers(app);
  return app;
}
Example #4
0
module.exports = function(app) {

    // app.use(function *(next){
    //     //config 注入中间件,方便调用配置信息
    //     if(!this.glob){
    //         this.glob = glob;
    //     }
    //     yield next;
    // });

    // responseTime
    app.use(cors());
    app.use(bodyParser());
    
    app.use(responseTime());
    // app.use(compress());
    // app.keys = ['session'];
    // app.use(session(app));
    onerror(app);

    app.use(serve(path.join(__dirname,'../../static')));
}
Example #5
0
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

// const index = require('./routes/index')
// const users = require('./routes/users')
const post = require('./routes/post')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
function render(controller, action) {
  var method = require('./app/controllers/' + controller)[action];
  return function*() {
    var response = yield method(this.query, this.params, this.request.body, this.request);
    this.body = response[1];
    this.status = response[0];
  };
}


/* routes start */

routes.get(  '/todos',                     render('todos',     'all'));
routes.post( '/todos',        bodyParser,  render('todos',     'create'));
routes.get(  '/todos/:id',                 render('todos',     'show'));
routes.del(  '/todos/:id',                 render('todos',     'delete'));
routes.patch('/todos/:id',    bodyParser,  render('todos',     'update'));
routes.del(  '/todos',                     render('todos',     'deleteAll'));

/* routes end */


app.use(require('./app/middlewares/request_logger')());
app.use(json());
app.use(cors({methods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE']}));
app.use(routes.middleware());

errorHandler(app);

app.listen(Number(process.env.PORT || 9000));
Example #7
0
'use strict'
const koa = require('koa')
const Router = require('koa-router')
const request = require('request')
const sharp = require('sharp')
const Stream = require('stream')
const onerror = require('koa-onerror')

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

onerror(app, {accepts() {return 'json'}})

function getImage(cb) {
  const url = this.query.url
  if (!url) {
    return cb(new Error('no image url provided'))
  }

  let contentType = ''
  let imageType = 'jpeg'

  const width = this.query.width && parseInt(this.query.width)
  const height = this.query.height && parseInt(this.query.height)
  const transform = function () {
    return toBuffer(sharp().resize(width, height)[imageType]())
  }
  function toBuffer(fn) {
    return fn.toBuffer((err, buf, info) => {
      if (err) {
        return cb(err)
Example #8
0
    this.throw(404);
});

// Error handle
onerror(app, {
    json: function(err) {
        var data = err.data || {};
        var statusCode = err.status;

        // Boom error
        if(err.output) {
            statusCode = err.output.statusCode;
        }

        data.status = statusCode || 500;
        if(!data.message) {
            data.message = err.message;
        }

        if(app.env === 'development') {
            data.stack = err.stack.split('\n');
        }

        this.status = data.status;
        this.body = data;
    }
});

// Error report
if(app.env !== 'development') {
    app.on('error', function(err) {
Example #9
0
app.use(convert(json()))
app.use(convert(logger()))

// static
app.use(convert(koaStatic(path.join(__dirname, '../public'), {
  pathPrefix: ''
})))

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

// 500 error
koaOnError(app, {
  template: 'views/500.ejs'
})

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

router.use('/', index.routes(), index.allowedMethods())
router.use('/users', users.routes(), users.allowedMethods())

// response
app.use(router.routes(), router.allowedMethods())
Example #10
0
.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'
})

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(router.routes(), router.allowedMethods())

// router config
router.use('/', index.routes())
router.use('/users', users.routes())
Example #11
0
Server.prototype.start = function () {

    let logger = Logger({
        dir: config.logDir,
        categories: ['router', 'model', 'controller', 'job'],
        format: 'YYYY-MM-DD-[{category}][.log]'
    });

    let port = this.opts.port || 3000;

    this.use(converter(session({
        store: redisStore({})
    })));
    this.keys = ['heavenduke'];
    this.use(converter(astepback()));
    this.use(converter(flash({})));

    this.context.logger = logger;

    onerror(this);

    new koaPug({
        viewPath: './view',
        debug: false,
        pretty: true,
        compileDebug: false,
        app: this
    });

    this.use(converter(bodyParser({
        formLimit: "100mb",
        jsonLimit: "100mb",
        textLimit: "100mb"
    })));
    this.use(converter(override()));

    this.use(converter(validator()));

    //静态文件cache
    let staticDir = config.staticDir;

    this.use(converter(koaStatic(path.join(staticDir, 'uploads'))));

    this.use(converter(staticCache(staticDir)));
    this.use(converter(staticCache(path.join(staticDir, 'uploads'))));
    this.use(converter(staticCache(path.join(staticDir, 'dist'))));
    this.use(converter(staticCache(path.join(staticDir, 'img'))));
    this.use(converter(staticCache(path.join(staticDir, 'fonts'))));

    this.use(async (ctx, next) => {
        try{
            await next();
        } catch(e) {
            if (process.env.NODE_ENV != 'test') {
                console.log(e.message);
                console.log(e);
                logger.error(e);
            }
            ctx.render('./error');
        }
    });

    routerUtils.mount(this, routers);

    this.listen(port);
    
    console.log('listening on port %s',config.port);
};
Example #12
0
function beautifyError(app) {
    onerror(app)
}
Example #13
0
module.exports = app => {
  // logging error
  const config = app.config.onerror;
  const viewTemplate = fs.readFileSync(config.templatePath, 'utf8');

  app.on('error', (err, ctx) => {
    ctx = ctx || app.createAnonymousContext();
    if (config.appErrorFilter && !config.appErrorFilter(err, ctx)) return;

    const status = detectStatus(err);
    // 5xx
    if (status >= 500) {
      try {
        ctx.logger.error(err);
      } catch (ex) {
        app.logger.error(err);
        app.logger.error(ex);
      }
      return;
    }

    // 4xx
    try {
      ctx.logger.warn(err);
    } catch (ex) {
      app.logger.warn(err);
      app.logger.error(ex);
    }
  });

  const errorOptions = {
    // support customize accepts function
    accepts() {
      const fn = config.accepts || accepts;
      return fn(this);
    },

    html(err) {
      const status = detectStatus(err);
      const errorPageUrl = typeof config.errorPageUrl === 'function'
        ? config.errorPageUrl(err, this)
        : config.errorPageUrl;

      // keep the real response status
      this.realStatus = status;
      // don't respond any error message in production env
      if (isProd(app)) {
        // 5xx
        if (status >= 500) {
          if (errorPageUrl) {
            const statusQuery =
              (errorPageUrl.indexOf('?') > 0 ? '&' : '?') +
              `real_status=${status}`;
            return this.redirect(errorPageUrl + statusQuery);
          }
          this.status = 500;
          this.body = `<h2>Internal Server Error, real status: ${status}</h2>`;
          return;
        }
        // 4xx
        this.status = status;
        this.body = `<h2>${status} ${http.STATUS_CODES[status]}</h2>`;
        return;
      }
      // show simple error format for unittest
      if (app.config.env === 'unittest') {
        this.status = status;
        this.body = `${err.name}: ${err.message}\n${err.stack}`;
        return;
      }

      const errorView = new ErrorView(this, err, viewTemplate);
      this.body = errorView.toHTML();
    },

    json(err) {
      const status = detectStatus(err);
      let errorJson = {};

      this.status = status;
      const code = err.code || err.type;
      const message = detectErrorMessage(this, err);

      if (isProd(app)) {
        // 5xx server side error
        if (status >= 500) {
          errorJson = {
            code,
            // don't respond any error message in production env
            message: http.STATUS_CODES[status],
          };
        } else {
          // 4xx client side error
          // addition `errors`
          errorJson = {
            code,
            message,
            errors: err.errors,
          };
        }
      } else {
        errorJson = {
          code,
          message,
          errors: err.errors,
        };

        if (status >= 500) {
          // provide detail error stack in local env
          errorJson.stack = err.stack;
          errorJson.name = err.name;
          for (const key in err) {
            if (!errorJson[key]) {
              errorJson[key] = err[key];
            }
          }
        }
      }

      this.body = errorJson;
    },

    js(err) {
      errorOptions.json.call(this, err, this);

      if (this.createJsonpBody) {
        this.createJsonpBody(this.body);
      }
    },
  };

  // support customize error response
  [ 'all', 'html', 'json', 'text', 'js' ].forEach(type => {
    if (config[type]) errorOptions[type] = config[type];
  });
  onerror(app, errorOptions);
};
Example #14
0
const config = getConfig()

let app = koa()
let router = routes()

// response-time middleware
app.use(function*(next) {
  var start = new Date
  yield next
  var ms = new Date - start
  this.set('X-Response-Time', ms + 'ms')
})

// error handler
onerror(app, {
  all: true
})

app.keys = [global.secret]
// use middleware
app.use(session(app, {
  signed: true
}))
app.use(logger())
app.use(compress())
app.use(bodyParser())

// static server
app.use(staticServe(path.join(__dirname, '../client/dist/')))

// koa-hbs is middleware. `use` it before you want to render a view
Example #15
0
Server.prototype.start = function () {

    var logger = Logger({
        dir: config.logDir,
        categories: ['router', 'model', 'controller', 'job'],
        format: 'YYYY-MM-DD-[{category}][.log]'
    });



    var port = this.opts.port || 3000;

    this.use(session(this));
    this.keys = ['heavenduke'];
    this.use(flash());

    this.context.logger = logger;
    onerror(this);

    var jade = new koaJade({
        viewPath: './view',
        debug: false,
        pretty: true,
        compileDebug: false,
        app: this
    });

    this.use(bodyParser());
    this.use(override());

    this.use(validator());

    //静态文件cache
    var staticDir = config.staticDir;

    this.use(koaStatic(path.join(staticDir, 'uploads')));

    this.use(staticCache(staticDir));
    this.use(staticCache(path.join(staticDir, 'vendors')));
    this.use(staticCache(path.join(staticDir, 'uploads')));
    this.use(staticCache(path.join(staticDir, 'js')));
    this.use(staticCache(path.join(staticDir, 'img')));
    this.use(staticCache(path.join(staticDir, 'css')));
    this.use(staticCache(path.join(staticDir, 'fonts')));
    this.use(staticCache(path.join(staticDir, 'bower_components')));
    plugins.static_init(this);
    this.use(function *(next) {
        try{
            yield* next;
        } catch(e) {
            if (process.env.NODE_ENV != 'test') {
                console.log(e.message);
                console.log(e);
                logger.error(e);
            }
            this.render('./error');
        }
    });

    this.use(router(this));

    appRouter(this);
    plugins.router_init(this);

    this.listen(port);

    this.on('error', function (err, ctx) {

    });
    
    console.log('listening on port %s',config.port);
};