四好公路
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

120 lines
3.4 KiB

'use strict';
/*jslint node:true*/
//from koa
const http = require('http');
const Koa = require('koa');
const convert = require('koa-convert');
const logger = require('koa-logger');
const session = require('koa-generic-session');
const bodyParser = require('koa-bodyparser');
const csrf = require('koa-csrf');
const cors = require('koa-cors');
const range = require('koa-range');
const statics = require('koa-static');
const Router = require('koa-66');
const io = require('socket.io');
//util
const co = require('co');
//from fs
const fsDc = require('fs-dc');
const fsLogger = require('fs-logger');
function scaffold(config) {
const defaultConfig = require('./config.js');
const app = new Koa();
csrf(app);
const router = new Router();
config = config || defaultConfig;
if (config.mws && config.mws.length) {//k8s探针用,去掉鉴权
config.mws = config.mws.map(v => {
if (v.opts && v.opts.exclude) {
if ('*' != v.opts.exclude[0]) {
v.opts.exclude.push({ p: '/healthz', o: 'GET' })
}
}
return v;
});
}
app.keys = ["it is a secret"];
app.use(convert(cors({
credentials: true
})));
app.use(co.wrap(errorHandler()));
app.use(range);
if (config.staticDirs && Array.isArray(config.staticDirs)) {
config.staticDirs.forEach(function (s) {
app.use(convert(statics(s)));
});
}
app.use(convert(logger()));
app.use(convert(session({ key: 'fs-sid', cookie: { maxAge: null } }, app)));
app.use(convert(bodyParser({
'formLimit': '80mb',
'jsonLimit': '80mb',
'textLimit': '80mb',
})));
//init fs.logger and inject it into app(app.fs.logger) and runtime ctx(ctx.fs.logger)
app.use(co.wrap(fsLogger(app, config.logger)));
//init fs.dc and inject it into app(app.fs.dc) and runtime ctx(app.fs.dc)
if (config.dc) {
app.use(co.wrap(fsDc(app, config.dc)));
}
const socketRegEvent = []
app.socket = {
on: function (evt, callback) {
socketRegEvent.push([evt, callback]);
}
}
config.mws.forEach(function (mv) {
if (typeof mv.entry === 'function') {
try {
mv.entry(app, router, mv.opts);
} catch (err) {
app.fs.logger.log('error', '[app]', err)
}
}
});
app.use(router.routes());
router.get('/healthz', async function (ctx, next) {//k8s探针用
try {
ctx.status = 200;
ctx.body = 'ok';
} catch (err) {
ctx.fs.logger.log('error', '[app]', err)
}
});
function errorHandler() {
return function* (ctx, next) {
try {
yield next();
} catch (err) {
app.fs.logger.log("error", "[FS-ERRHD]", err);
//simple process.
//@Todo 500 page; 400...
ctx.status = 500;
ctx.body = 'internal server error';
}
};
}
const server = http.createServer(app.callback());
const socket = io(server);
app.socket = socket;
socketRegEvent.forEach(function (reg) {
socket.on(reg[0], reg[1]);
});
app.server = server.listen(config.port || 4000);
// app.server = app.listen(config.port || 4000);
//for test
app.router = router;
return app;
}
module.exports = scaffold;