Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
54 lines (46 loc) · 1.42 KB
/
Copy pathindex.js
File metadata and controls
54 lines (46 loc) · 1.42 KB
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
const R = require("ramda");
const groupValuesByKey = require("group-values-by-key");
/** Merge nested objects in a single object
*
* @param {Array[Object[]] || Object[]} objects objects to merge
* @return {Object} the new merged object
* @api private
*/
const nestedMergeAll = R.pipe(
R.flatten,
R.mergeAll
);
/** Configure a koa server with a provided configuration
*
* @param {Object} Koa - Koa builder
* @param {Object} config config
* @param {Object[]} [config.routers=[]] - koa routers
* @param {Object[]} [config.middleware=[]]- koa middlewares
* @param {Object[]} [config.ctx={}] - Items that must be added into koa context
* @param {Object[]} [config.presets=[]] - preconfigured set of middleware, routers and ctx
* @return {Object} configured Koa server ready to by started
* @api public
*/
const koaHandler = Koa => ({
routers = [],
middlewares = [],
ctx = {},
presets = []
}) => {
const app = new Koa();
const groupedItems = groupValuesByKey(presets);
// Load added context in app
const allCtx = nestedMergeAll([ctx, groupedItems.ctx]);
R.keys(allCtx).forEach(key => {
app.context[key] = allCtx[key];
});
// Load middlewares and routers in app
R.flatten([groupedItems.middlewares, middlewares]).forEach(middleware =>
app.use(middleware)
);
R.flatten([routers, groupedItems.routers]).forEach(router =>
app.use(router.routes())
);
return app;
};
module.exports = koaHandler;