forked from jksdua/koa-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (77 loc) · 2.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* jshint node:true, esnext:true */
'use strict';
const KF_VERSION = require('./package.json').version;
var koa = require('koa');
var merge = require('lodash').merge;
var assert = require('assert');
var router = require('koa-router');
var middleware = {
requestId: require('./middleware/request-id'),
parse: require('./middleware/parse'),
error: require('./middleware/error'),
logger: require('./middleware/logger'),
cors: require('./middleware/cors'),
noCache: require('./middleware/no-cache'),
gzip: require('./middleware/gzip'),
helmet: require('./middleware/helmet'),
vitalsigns: require('./middleware/vitalsigns'),
schema: require('./middleware/schema')
};
module.exports = exports = function(options) {
var app = koa();
app.KF_VERSION = KF_VERSION;
// print warning messages to console by default
// using `app.warn` allows users to turn this behaviour off by overriding this property
app.warn = exports.warn;
options = merge({}, {
middleware: Object.keys(middleware).reduce(function(opt, name) {
opt[name] = middleware[name].defaults;
assert(opt[name]);
return opt;
}, {}),
// options passed to koa-router when creating a router
router: {
throw: true
}
}, options);
var mOptions = options.middleware;
['requestId', 'gzip', 'logger', 'error', 'noCache', 'cors', 'parse'].forEach(function(i) {
if (mOptions[i].enabled) {
app.use(middleware[i](mOptions[i], app));
}
});
app.router = function(routerOpts) {
routerOpts = merge({}, options.router, routerOpts);
return new router(routerOpts);
};
app.Router = app.router;
app.mount = function() {
for (var i = 0, len = arguments.length; i < len; i += 1) {
var router = arguments[i];
app.use(router.routes());
app.use(router.allowedMethods());
}
};
// helmet (security)
if (mOptions.helmet.enabled) {
middleware.helmet(mOptions.helmet, app);
} else {
app.warn('helmet middleware disabled. It will be enabled by default in next major release');
}
// health route
if (mOptions.vitalsigns.enabled) {
middleware.vitalsigns(mOptions.vitalsigns, app);
} else {
app.warn('vitalsigns middleware disabled. It will be enabled by default in next major release');
}
// schema validator
app.schema = middleware.schema(mOptions.schema, app);
app.bundledMiddleware = middleware;
return app;
};
exports.KF_VERSION = KF_VERSION;
// global warn method
// allows global override for all app instances
exports.warn = console.warn;
// expose middleware so it can be used in more flexible ways
exports.middleware = exports.bundledMiddleware = middleware;